package xcmg.device.service.basic;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import xcmg.device.dao.entity.MaterialClassDO;
import xcmg.device.dao.entity.MaterialLocationRelationDO;
import xcmg.device.dao.entity.MaterialWarehouseUserDO;
import xcmg.device.dao.entity.PriMaterialsDO;
import xcmg.device.dao.entity.PubMaterialsDO;
import xcmg.device.dao.entity.basic.AuthDeviceLimitDO;
import xcmg.device.dao.entity.company.CompanyDealerDO;
import xcmg.device.dao.entity.company.CompanyDealerSelectedDO;
import xcmg.device.dao.entity.company.CompanyInfoDO;
import xcmg.device.dao.entity.company.CompanySupplierDO;
import xcmg.device.dao.entity.marketing.MarketingActivityDO;
import xcmg.device.dao.entity.taskRecord.TaskRecordDO;
import xcmg.device.dao.entity.warehouse.WarehouseAreaDO;
import xcmg.device.dao.entity.warehouse.WarehouseAreaLocationDO;
import xcmg.device.dao.entity.warehouse.WarehouseDO;
import xcmg.device.dao.mapper.CompanyDealerMapper;
import xcmg.device.dao.mapper.CompanyInfoMapper;
import xcmg.device.dao.mapper.CompanySupplierMapper;
import xcmg.device.dao.mapper.MarketingActivityMapper;
import xcmg.device.dao.mapper.MarketingMaterialsMapper;
import xcmg.device.dao.mapper.MaterialClassMapper;
import xcmg.device.dao.mapper.MaterialLocationRelationMapper;
import xcmg.device.dao.mapper.MaterialWarehouseUserMapper;
import xcmg.device.dao.mapper.PriMaterialsMapper;
import xcmg.device.dao.mapper.PubMaterialsMapper;
import xcmg.device.dao.mapper.SaleIntentionDetailMapper;
import xcmg.device.dao.mapper.basic.AuthDeviceLimitMapper;
import xcmg.device.dao.mapper.basic.MaterialsSupplierMapper;
import xcmg.device.dao.mapper.taskRecord.TaskRecordMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseAreaDOMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseAreaLocationDOMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseDOMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseDeliveryDetailMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseInventoryMapper;
import xcmg.device.infra.BeanUtil;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.ExcelUtil;
import xcmg.device.infra.ExportUtil;
import xcmg.device.infra.FileUtil;
import xcmg.device.infra.enums.CompanyTypeEnum;
import xcmg.device.infra.enums.PurchaseOrdTypeEnum;
import xcmg.device.infra.enums.TaskRecordEnum;
import xcmg.device.service.marketing.MarketingActivityService;
import xcmg.device.service.secondAgent.SecondAgentService;
import xcmg.device.service.vo.FunctionResult;
import xcmg.device.service.vo.ImportReplaceVO;
import xcmg.device.service.vo.basic.AuthConditionVO;
import xcmg.device.service.vo.basic.AuthDeviceLimitVO;
import xcmg.device.service.vo.basic.AuthDeviceOutVO;
import xcmg.device.service.vo.basic.DefaultLocationSearchVO;
import xcmg.device.service.vo.basic.MaterialLocationRelationVO;
import xcmg.device.service.vo.basic.MaterialWeightImportVO;
import xcmg.device.service.vo.basic.MaterialsRelationVO;
import xcmg.device.service.vo.basic.MaterialsSearchVO;
import xcmg.device.service.vo.basic.MaterialsSupplierVO;
import xcmg.device.service.vo.basic.MaterialsVO;
import xcmg.device.service.vo.basic.OemPriceSyncVO;
import xcmg.device.service.vo.company.CompanyBaseInfo;
import xcmg.device.service.vo.company.CompanyInfoVO;
import xcmg.device.service.vo.marketing.MarketingActivityPriceVO;
import xcmg.device.service.vo.marketing.MarketingActivityVO;
import xcmg.device.service.vo.marketing.MarketingMaterialsVO;
import xcmg.device.service.vo.secondAgent.SecondAgentVO;
import xcmg.device.service.vo.warehouse.InventoryMaterialsSearchVO;
import xcmg.device.service.vo.warehouse.InventoryMaterialsVO;
import xcmg.device.service.vo.warehouse.app.EnableAndOccupyVO;
import xcmg.device.service.warehouse.CommonService;
import xcmg.device.service.warehouse.WarehouseInventoryService;
import xcmg.device.util.CommonUtils;
import xcmg.device.util.CompanyUtil;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.util.ListUtil;
import yb.ecp.fast.infra.util.PageHelperPlus;
import yb.ecp.fast.infra.util.StringUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by GYJ on 2017-12-22.
 */
@Slf4j
@Service
@RefreshScope
public class MaterialsService  {
    @Autowired
    private PubMaterialsMapper pubMaterialsMapper;
    @Autowired
    private PriMaterialsMapper priMaterialsMapper;
    @Autowired
    private HttpServletResponse response;
    @Value("${spring.file.download.path}")
    private String filePath;

    @Autowired
    private WarehouseInventoryMapper warehouseInventoryMapper;
    @Autowired
    private CompanyInfoMapper companyInfoMapper;

    @Autowired
    private FastGenClient fastGenClient;
    @Autowired
    private MaterialWarehouseUserMapper materialWarehouseUserMapper;
    @Autowired
    private WarehouseAreaLocationDOMapper warehouseAreaLocationDOMapper;

    @Autowired
    private MarketingActivityService marketingActivityService;

    @Autowired
    private MaterialLocationRelationMapper materialLocationRelationMapper;

    @Autowired
    private MaterialClassMapper materialClassMapper;

    @Autowired
    private CommonService commonService;

    @Autowired
    private WarehouseDOMapper warehouseDOMapper;

    @Autowired
    private WarehouseAreaDOMapper warehouseAreaDOMapper;

    @Autowired
    private CompanySupplierMapper companySupplierMapper;

    @Autowired
    private MaterialsSupplierMapper materialsSupplierMapper;

    @Autowired
    private WarehouseDeliveryDetailMapper warehouseDeliveryDetailMapper;

    @Autowired
    private SaleIntentionDetailMapper saleIntentionDetailMapper;

    @Autowired
    private CompanyDealerMapper companyDealerMapper;

    /*
     * @Autowired private MaterialsService materialsService;
     */
    @Autowired
    private SecondAgentService secondAgentService;
    @Autowired
    private AuthDeviceLimitMapper authDeviceLimitMapper;

    @Autowired
    private TaskRecordMapper taskRecordMapper;

    @Autowired
    private WarehouseInventoryService warehouseInventoryService;

    @Autowired
    private CompanyUtil companyUtil;

    private String templateExcelFileName = "MaterialsImport.xls";

    private String templatePurchaseInExcelFileName = "PurchaseInImport.xls";
    private String templateLocationExcelFileName = "MaterialLocation.xls";
    
    private String templateAuthExcelFileName = "MaterialAuth.xls";

    private String templateTyprEntranceCrucial = "MaterialTyprEntranceCrucial.xls";

    private String templateReplace = "ReplaceMaterials.xls";

    private String templateKeeper = "MaterialWarehouseUser.xls";

    private String templateGroupPurExcelFileName = "MaterialsGroupPur.xls";

    private String templateCompanyPrice = "CompanyMaterialsPrice.xls";

    private String templateDealerPrice = "DealerMaterialsPrice.xls";

    //零件重量导入模板
    private static final String MATERIAL_WEIGHT_EXCELNAME = "MaterialsWeightTemplete.xls";

    @Autowired
    private MarketingActivityMapper marketingActivityMapper;

    @Autowired
    private MarketingMaterialsMapper marketingMaterialsMapper;

    private static void takeDecimals(MaterialsVO model) {
        if (model.getStandardPrice() != null) {
            model.setStandardPrice(model.getStandardPrice().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
        }
        if (model.getPrice() != null) {
            model.setPrice(model.getPrice().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
        }
        if (model.getMovingAveragePrice() != null) {
            model.setMovingAveragePrice(model.getMovingAveragePrice().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
        }
        if (model.getGuidePrice() != null) {
            model.setGuidePrice(model.getGuidePrice().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
        }
        if (model.getAgentPurchasePrice() != null) {
            model.setAgentPurchasePrice(model.getAgentPurchasePrice().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
        }
        if (model.getParityPrice() != null) {
            model.setParityPrice(model.getParityPrice().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
        }
    }
    public PageCommonVO<MaterialsVO> list(SearchCommonVO<MaterialsSearchVO> condition) {
        PageCommonVO<MaterialsVO> result = new PageCommonVO<>();
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<MaterialsVO> resultList = new ArrayList<>();
        if (!StringUtils.isEmpty(condition.getFilters().getMaterialsNos())) {
            String splitString = ",";
            if (condition.getFilters().getMaterialsNos().trim().contains("\n")) {
                splitString = "\n";
            }
            String[] str = condition.getFilters().getMaterialsNos().trim().replace("，", ",").split(splitString);
            condition.getFilters().setMaterialsList(Arrays.asList((str)));
        }
        if (!StringUtils.isEmpty(condition.getFilters().getCustomMaterialsNos())) {
            String[] str = condition.getFilters().getCustomMaterialsNos().trim().replace("，", ",").split(",");
            condition.getFilters().setCustomMaterialsList(Arrays.asList((str)));
        }
        if (StringUtils.isEmpty(condition.getFilters().getWarehouseCode())) {
            PageHelperPlus.orderBy("create_date desc, MATERIALS_NO desc");
            resultList = priMaterialsMapper.list(condition.getFilters());
            for (MaterialsVO model : resultList) {
                takeDecimals(model);
            }
        } else {
            PageHelperPlus.orderBy("create_date desc");
            resultList = priMaterialsMapper.list(condition.getFilters());
        }

        //获取零售目录指导价
        String orgId = condition.getFilters().getOrgId();
        resultList.forEach(x -> x.setGuidePrice(priMaterialsMapper.getGuidePrice(x.getMaterialsNo(), orgId)));

        result.setPageInfo(new PageInfo(resultList));
        result.setPageInfoList(resultList);
        return result;
    }



    public PageCommonVO<MaterialsVO> querySupplierMaterials(SearchCommonVO<MaterialsSearchVO> condition) {
        PageCommonVO<MaterialsVO> result = new PageCommonVO<>();
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        PageHelperPlus.orderBy("MATERIALS_NO asc");
        List<MaterialsVO> resultList  = priMaterialsMapper.querySupplierMaterials(condition.getFilters());
        result.setPageInfo(new PageInfo(resultList));
        result.setPageInfoList(resultList);
        return result;
    }



    public PageCommonVO<MaterialsSupplierVO> querySupplierList(SearchCommonVO<MaterialsSupplierVO> condition, String orgId) {
        PageCommonVO<MaterialsSupplierVO> result = new PageCommonVO<>();
        MaterialsSupplierVO v = condition.getFilters();
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<MaterialsSupplierVO> resultList =  priMaterialsMapper.querySupplierList(v);
        result.setPageInfo(new PageInfo(resultList));
        result.setPageInfoList(resultList);
        return result;
    }


    public PageCommonVO<MaterialsVO> listForOut(SearchCommonVO<MaterialsVO> condition) {
        PageCommonVO<MaterialsVO> result = new PageCommonVO<>();
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        PageHelperPlus.orderBy("create_date desc");
        MaterialsVO materialsParam = condition.getFilters();
        List<MaterialsVO> resultList = priMaterialsMapper.listForOut(materialsParam);
        for (MaterialsVO materialsVO : resultList) {
            materialsVO.setEnableNum(warehouseInventoryMapper.findEnableNum(materialsVO.getMaterialsNo(), materialsParam.getOrgId(), materialsParam.getWarehouseCode()));
            materialsVO.setDeliveryNum(warehouseDeliveryDetailMapper.findOccupyNum(materialsVO.getMaterialsNo(), materialsParam.getOrgId(), materialsParam.getWarehouseCode()));
            materialsVO.setIntentionNum(saleIntentionDetailMapper.findOccupyNum(materialsVO.getMaterialsNo(), materialsParam.getOrgId()));
        }
        result.setPageInfo(new PageInfo(resultList));
        result.setPageInfoList(resultList);
        return result;
    }

    /**
     * 零件检索，根据采购价格维护表进行过滤
     *
     * @param condition
     * @param orgId
     * @return
     * @throws Exception
     */
    public PageCommonVO<MaterialsVO> purchaseMaterialsListByFilter(SearchCommonVO<MaterialsSearchVO> condition, String orgId, Boolean selfMaterialFlag) throws Exception {
        condition.getFilters().setDeviceTypes(null);
        if (!StringUtil.isNullOrEmpty(condition.getFilters().getOrgId()) && !condition.getFilters().getOrgId().equals(orgId)) {
            CompanySupplierDO supplierDO = companySupplierMapper.itemBySupplierOrgId(orgId, condition.getFilters().getOrgId());
            if (supplierDO == null || !supplierDO.getIsPlatCompany()) {
                condition.getFilters().setOrgId(orgId);
            }
        }
        boolean direct0=Integer.valueOf(0).equals(condition.getFilters().getIsDirectCast())||Integer.valueOf(0).equals(condition.getFilters().getIsDirectCastHF());
        if(direct0 && selfMaterialFlag) {
            condition.getFilters().setOrgId(orgId);
        }

        if(StringUtils.isNotEmpty(condition.getFilters().getOemOrgId())) {
            condition.getFilters().setOrgId(condition.getFilters().getOemOrgId());
        }

        if(StringUtils.isNotEmpty(condition.getFilters().getOrgId())) {
            List<AuthDeviceLimitDO> authDeviceLimitDOs = authDeviceLimitMapper.getInfos(condition.getFilters().getOrgId(), orgId);
            List<Integer> deviceTypes = new ArrayList<Integer>();
            for(AuthDeviceLimitDO authDeviceLimitDO: authDeviceLimitDOs) {
                deviceTypes.add(authDeviceLimitDO.getDeviceType());
            }
            condition.getFilters().setDeviceTypes(deviceTypes);
        }

        PageCommonVO<MaterialsVO> result = new PageCommonVO<>();
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<MaterialsVO> resultList = new ArrayList<>();
        List<MaterialsVO> resultLists = new ArrayList<>();
        PageHelperPlus.orderBy("create_date desc");
        MaterialsSearchVO searchFilter = condition.getFilters();
        // 集购零件条件
        Integer isGroupPur = PurchaseOrdTypeEnum.getGroupTypeByOrderType(searchFilter.getPurchaseOrdType());
        searchFilter.setIsGroupPur(isGroupPur);
        searchFilter.setMaterialsList(xcmg.device.infra.StringUtil.splitList(searchFilter.getMaterialsNos()));
        resultList = priMaterialsMapper.listByFilter(searchFilter);
        CompanyDealerDO companyDealerDO = companyDealerMapper.itemByOrgId(orgId, searchFilter.getDealerOrgId());
        Map<String, BigDecimal> ynInventoryMap=marketingActivityService.queryYnInventoryMap(resultList,null);

        for (MaterialsVO model : resultList) {
            newestReplace(model);
            takeDecimals(model);
            MarketingActivityPriceVO marInfo = marketingActivityService.activityPriceModel(companyDealerDO, searchFilter.getOrgId(), model.getMaterialsNo());
            model.setSettlementPrice(model.getPrice());
            if (marInfo != null) {
                model.setSettlementPrice(marInfo.getDiscountPrice());
                model.setPriceSchemeId(marInfo.getActivityId());
                model.setPriceSchemeName(marInfo.getName());
            }
            // 获取评级折扣价
//            MarketingActivityPriceVO activityPriceVO = marketDealerRatingService.activityPriceModel(companyDealerDO, searchFilter.getOrgId(), model.getMaterialsNo());
//            if (activityPriceVO != null) {
//                model.setSettlementPrice(activityPriceVO.getDiscountPrice());
//                model.setPriceSchemeId(activityPriceVO.getActivityId());
//                model.setPriceSchemeName(activityPriceVO.getName());
//            }
//
            EnableAndOccupyVO enableAndOccupyVO = warehouseInventoryService.findEnableAndOccupyNum2(model.getMaterialsNo(), model.getOrgId(), null,ynInventoryMap);
            if (enableAndOccupyVO != null) {
                model.setIntentionNum(enableAndOccupyVO.getIntentionNum());
                model.setDeliveryNum(enableAndOccupyVO.getDeliveryNum());
                BigDecimal allAmount = enableAndOccupyVO.getEnableNum()==null?BigDecimal.ZERO:enableAndOccupyVO.getEnableNum();
                BigDecimal occupyAmount = enableAndOccupyVO.getDeliveryNum()==null?BigDecimal.ZERO:enableAndOccupyVO.getDeliveryNum();
//                BigDecimal intentionAmount = enableAndOccupyVO.getIntentionNum()==null?BigDecimal.ZERO:enableAndOccupyVO.getIntentionNum();
                model.setEnableNum(allAmount.subtract(occupyAmount));
//                DataDictionaryDO dataDictionaryDO = dataDictionaryMapper.itemByCode("KYKC", model.getOrgId());
//                if(dataDictionaryDO != null) {
//                	model.setEnableNum(model.getEnableNum().subtract(intentionAmount));
//                }
            }
            List<MarketingActivityPriceVO> MarketingActivityDOList = marketingActivityService.activityPriceList(searchFilter.getDealerOrgId(), searchFilter.getOrgId(), model.getMaterialsNo());
            model.setMarketingActivityPriceVOList(MarketingActivityDOList);
            resultLists.add(model);
        }

        result.setPageInfo(new PageInfo(resultList));
        result.setPageInfoList(resultLists);
        return result;
    }

    /**
     * 获取最新的替换和改型零件
     */
    private void newestReplace(MaterialsVO model) {
        PriMaterialsDO replaceDo = new PriMaterialsDO();
        BeanUtils.copyProperties(model, replaceDo);
        if (model.getReplaceMaterialsNo() != null) {
            Set<String> replaceNo = new HashSet<>();
            Set<String> replaceDes = new HashSet<>();
            getPriMaterialsDO(replaceDo, replaceNo, replaceDes);
            model.setReplaceMaterialsNo(StringUtils.join(replaceNo, ","));
            model.setReplaceMaterialsDes(StringUtils.join(replaceDes, ","));
        }
        PriMaterialsDO retrofit = null;
        PriMaterialsDO retrofitDo = new PriMaterialsDO();
        BeanUtils.copyProperties(model, retrofitDo);
        int retInt = 0;
        if (model.getRetrofitMaterialsNo() != null) {
            do {
                retInt++;
                retrofit = retrofitDo;
                if (retrofitDo.getRetrofitMaterialsNo() == null || retrofitDo.getRetrofitMaterialsNo().equals(retrofitDo.getMaterialsNo())) {
                    break;
                }
                if (retInt > 20) {
                    break;
                }
                retrofitDo = priMaterialsMapper.itemByNo(retrofitDo.getRetrofitMaterialsNo(), retrofitDo.getOrgId());
            } while (retrofitDo != null);
            if (retrofit != null) {
                model.setRetrofitMaterialsNo(retrofit.getMaterialsNo());
                model.setRetrofitMaterialsDes(retrofit.getMaterialsDes());
            }
        }
    }

    private void getPriMaterialsDO(PriMaterialsDO replaceDo, Set<String> replaceNo, Set<String> replaceDes) {
        if (null == replaceDo) {
            return;
        }

        String[] arrReplaceMaterialsNo = replaceDo.getReplaceMaterialsNo().split(",");
        for (String replaceMaterialsNo : arrReplaceMaterialsNo) {
            int repInt = 0;
            PriMaterialsDO replace = replaceDo;
            if (replaceMaterialsNo.equals(replaceDo.getMaterialsNo())) {
                replaceNo.add(replaceDo.getMaterialsNo());
                replaceDes.add(replaceDo.getMaterialsDes());
                continue;
            }
            replaceDo = priMaterialsMapper.itemByNo(replaceMaterialsNo, replaceDo.getOrgId());
            if (null == replaceDo) {
                replaceNo.add(replace.getMaterialsNo());
                replaceDes.add(replace.getMaterialsDes());
                continue;
            }
            if (StringUtils.isBlank(replaceDo.getReplaceMaterialsNo())) {
                replaceNo.add(replaceDo.getMaterialsNo());
                replaceDes.add(replaceDo.getMaterialsDes());
                continue;
            }
            getPriMaterialsNO(replaceDo, replaceNo, replaceDes, repInt);
        }
    }

    private void getPriMaterialsNO(PriMaterialsDO replaceDo, Set<String> replaceNo, Set<String> replaceDes, int repInt) {
        if (null == replaceDo) {
            return;
        }
        String[] arrReplaceMaterialsNo = replaceDo.getReplaceMaterialsNo().split(",");
        for (String replaceMaterialsNo : arrReplaceMaterialsNo) {
            if (repInt > 20) {
                replaceNo.add(replaceDo.getMaterialsNo());
                replaceDes.add(replaceDo.getMaterialsDes());
                continue;
            }
            repInt++;
            PriMaterialsDO replace = replaceDo;
            if (replaceMaterialsNo.equals(replaceDo.getMaterialsNo())) {
                replaceNo.add(replaceDo.getMaterialsNo());
                replaceDes.add(replaceDo.getMaterialsDes());
                continue;
            }
            replaceDo = priMaterialsMapper.itemByNo(replaceMaterialsNo, replaceDo.getOrgId());
            if (null == replaceDo) {
                replaceNo.add(replace.getMaterialsNo());
                replaceDes.add(replace.getMaterialsDes());
                continue;
            }
            if (StringUtils.isBlank(replaceDo.getReplaceMaterialsNo())) {
                replaceNo.add(replaceDo.getMaterialsNo());
                replaceDes.add(replaceDo.getMaterialsDes());
                continue;
            }
            getPriMaterialsNO(replaceDo, replaceNo, replaceDes, repInt);
        }
    }

    public PageCommonVO listByCode(SearchCommonVO<InventoryMaterialsSearchVO> condition) {
        PageCommonVO pageCommonVO = new PageCommonVO();
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<MaterialsVO> voList = new ArrayList<>();
        List<InventoryMaterialsVO> results = warehouseInventoryMapper.invenitoryMaterialsList(condition.getFilters());
        for (InventoryMaterialsVO materialsVO : results) {
            MaterialsVO vo = new MaterialsVO();
            BeanUtils.copyProperties(materialsVO, vo);
            vo.setMaterialsDes(materialsVO.getMaterialsName());
            vo.setAmount(materialsVO.getAmount());
            vo.setStockLocation(materialsVO.getLocationCode());
            vo.setUserName(materialsVO.getUserName());
            vo.setBarCode(materialsVO.getBarCode());
            voList.add(vo);
        }
        pageCommonVO.setPageInfo(new PageInfo(results));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    @Transactional
    public ErrorCode add(MaterialsVO materialsVO) {
        if (priMaterialsMapper.count(materialsVO.getMaterialsNo(), materialsVO.getOrgId()) > 0) {
            return ErrorCode.MaterialsNoIsExists;
        }
        PriMaterialsDO entity = new PriMaterialsDO();
        BeanUtils.copyProperties(materialsVO, entity);
        rounding(entity);
        if (priMaterialsMapper.insert(entity) == 0) {
            return ErrorCode.MaterialsInsertFail;
        }

        //更新零件英文描述
        insertOrUpdateMaterialsLocal(materialsVO,0);

        //主机厂端添加图片同步修改代理商端
        priMaterialsMapper.sysnUpdateImage(entity);

        for (MaterialsRelationVO materialsRelationVO : materialsVO.getMaterialsRelationList()) {
            if (StringUtil.isNullOrEmpty(materialsRelationVO.getLocationCode()) || StringUtil.isNullOrEmpty(materialsRelationVO.getUserId())) {
                continue;
            }
            MaterialWarehouseUserDO materialWarehouseUserDO = new MaterialWarehouseUserDO();
            ActionResult<String> id = fastGenClient.textGuid();
            if (id == null || id.getCode() != 0) {
                return ErrorCode.Failure;
            }
            BeanUtils.copyProperties(materialsRelationVO, materialWarehouseUserDO);
            //内部主键
            materialWarehouseUserDO.setId(id.getValue());
            materialWarehouseUserDO.setOrgId(materialsVO.getOrgId());
            materialWarehouseUserDO.setMaterialsNo(materialsVO.getMaterialsNo());
            materialWarehouseUserMapper.insert(materialWarehouseUserDO);
        }
        return ErrorCode.Success;
    }

    /**
     * 新增或更新零件英文描述
     * @param pubMaterialsDO
     * @param flag 0新增   1修改
     */
    private void insertOrUpdateMaterialsLocal(PubMaterialsDO pubMaterialsDO,int flag) {
        if (pubMaterialsMapper.countMaterialsLocal(pubMaterialsDO.getMaterialsNo()) == 0) {
            pubMaterialsDO.setCreateDate(new Date());
            pubMaterialsDO.setUpdateId(null);
            pubMaterialsMapper.insertMaterialsLocal(pubMaterialsDO);
        }else{
            pubMaterialsDO.setUpdateDate(new Date());
            pubMaterialsDO.setCreateId(null);
            pubMaterialsMapper.updateMaterialsLocal(pubMaterialsDO);
        }
    }


    /**
     * 新增或更新零件英文描述
     * @param materialsVO
     * @param flag 0新增   1修改
     */
    private void insertOrUpdateMaterialsLocal(MaterialsVO materialsVO,int flag) {
        PubMaterialsDO pubMaterialsDO = new PubMaterialsDO();
        pubMaterialsDO.setMaterialsNo(materialsVO.getMaterialsNo());
        pubMaterialsDO.setMaterialsDesEn(materialsVO.getMaterialsDesEn());
        if (flag == 0) {
            pubMaterialsDO.setCreateId(materialsVO.getCreateId());
            pubMaterialsDO.setUpdateId(materialsVO.getCreateId());
        }else{
            pubMaterialsDO.setCreateId(materialsVO.getUpdateId());
            pubMaterialsDO.setUpdateId(materialsVO.getUpdateId());
        }
        this.insertOrUpdateMaterialsLocal(pubMaterialsDO, flag);
    }

    private static void rounding(PriMaterialsDO entity) {
        if (entity.getPrice() != null) {
            //取整
            entity.setPrice(entity.getPrice().multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP));
        }
        if (entity.getStandardPrice() != null) {
            //取整
            entity.setStandardPrice(entity.getStandardPrice().multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP));
        }
        if (entity.getMovingAveragePrice() != null) {
            //取整
            entity.setMovingAveragePrice(entity.getMovingAveragePrice().multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP));
        }
    }

    public PageCommonVO<MaterialsVO> purchaseMaterialsList(SearchCommonVO<MaterialsSearchVO> condition, String orgId, Boolean selMaterialFlag) throws Exception {
        condition.getFilters().setDeviceTypes(null);
        if (!StringUtil.isNullOrEmpty(condition.getFilters().getOrgId()) && !condition.getFilters().getOrgId().equals(orgId)) {
            CompanySupplierDO supplierDO = companySupplierMapper.itemBySupplierOrgId(orgId, condition.getFilters().getOrgId());
            if (supplierDO == null || !supplierDO.getIsPlatCompany()) {
                condition.getFilters().setOrgId(orgId);
            }
        }
        boolean direct0 = Integer.valueOf(0).equals(condition.getFilters().getIsDirectCast()) || Integer.valueOf(0).equals(condition.getFilters().getIsDirectCastHF());
        if (direct0) {
            if (selMaterialFlag) {
                condition.getFilters().setOrgId(orgId);
            } else {
                String dealerOrgId = StringUtils.isEmpty(condition.getFilters().getDealerOrgId()) ? orgId : condition.getFilters().getDealerOrgId();
                CompanyDealerDO companyDealerDO = companyDealerMapper.getDealerByPlatOrgId(companyUtil.ynOrgId(), dealerOrgId);
                if (companyDealerDO != null) {
                    condition.getFilters().setNormalType(1);
                }
            }
        }

        String oemOrgId = condition.getFilters().getOemOrgId();
        String receiveOrgId = condition.getFilters().getOrgId();
        String supplierOrgId = condition.getFilters().getSupplierOrgId();
        //Integer isDirectCast = condition.getFilters().getIsDirectCast();
        boolean direct1 = Integer.valueOf(1).equals(condition.getFilters().getIsDirectCast()) || Integer.valueOf(1).equals(condition.getFilters().getIsDirectCastHF());

        if (StringUtils.isNotEmpty(oemOrgId)) {
            condition.getFilters().setOrgId(oemOrgId);
        }

        if (StringUtils.isNotEmpty(condition.getFilters().getOrgId())) {
            List<AuthDeviceLimitDO> authDeviceLimitDOs = authDeviceLimitMapper.getInfos(condition.getFilters().getOrgId(), orgId);
            List<Integer> deviceTypes = new ArrayList<Integer>();
            for (AuthDeviceLimitDO authDeviceLimitDO : authDeviceLimitDOs) {
                deviceTypes.add(authDeviceLimitDO.getDeviceType());
            }
            condition.getFilters().setDeviceTypes(deviceTypes);
        }

        if (direct1 && StringUtils.isNotEmpty(condition.getFilters().getSupplierOrgId())) {
            CompanyInfoDO companyInfoDO = companyInfoMapper.item(condition.getFilters().getSupplierOrgId());
            if (null != companyInfoDO && null != companyInfoDO.getCompanyType() && "1".equals(companyInfoDO.getCompanyType())) {
                MaterialsSearchVO filters = condition.getFilters();
                filters.setOrgId(condition.getFilters().getSupplierOrgId());
                filters.setSupplierOrgId(null);
                filters.setIsDirectCast(0);
                filters.setIsDirectCastHF(0);
            }
        }

        PageCommonVO<MaterialsVO> result = new PageCommonVO<>();
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<MaterialsVO> resultList = new ArrayList<>();
        List<MaterialsVO> resultLists = new ArrayList<>();
        PageHelperPlus.orderBy("create_date desc, MATERIALS_NO desc");
        MaterialsSearchVO searchFilter = condition.getFilters();
        // 集购零件条件
        Integer isGroupPur = PurchaseOrdTypeEnum.getGroupTypeByOrderType(searchFilter.getPurchaseOrdType());
        searchFilter.setIsGroupPur(isGroupPur);
        searchFilter.setMaterialsList(xcmg.device.infra.StringUtil.splitList(searchFilter.getMaterialsNos()));
        resultList = priMaterialsMapper.list(searchFilter);
        CompanyDealerDO companyDealerDO = companyDealerMapper.itemByOrgId(receiveOrgId, searchFilter.getDealerOrgId());
        //二级代理商直发订单
        if (null != companyDealerDO && null != companyDealerDO.getDealerType()
                && companyDealerDO.getDealerType() == 2
                && null != companyDealerDO.getDealerLevel()
                && companyDealerDO.getDealerLevel() == 2
                && direct1) {
            receiveOrgId = supplierOrgId;//云内orgId
        }
        //云内价格Map
        Map<String, MarketingActivityPriceVO> ynPriceMap = marketingActivityService.queryYnPriceMap(resultList);
        Map<String, BigDecimal> ynInventoryMap = marketingActivityService.queryYnInventoryMap(resultList, searchFilter.getSupplierOrgId());

        for (MaterialsVO model : resultList) {
            if (StringUtils.isNotEmpty(oemOrgId)) {
                PriMaterialsDO materialsDO = priMaterialsMapper.getInfoByMaterialsNo(model.getMaterialsNo(), receiveOrgId);
                model.setPrice(materialsDO != null ? materialsDO.getPrice() : null);
            }
            newestReplace(model);
            takeDecimals(model);
            MarketingActivityPriceVO marInfo = marketingActivityService.activityPriceModelByName(companyDealerDO, receiveOrgId, model.getMaterialsNo(), direct1);
            model.setSettlementPrice(model.getPrice());
            if (marInfo != null) {
                model.setSettlementPrice(marInfo.getDiscountPrice());
                model.setPriceSchemeId(marInfo.getActivityId());
                model.setPriceSchemeName(marInfo.getName());
            }
            MarketingActivityPriceVO ynpv = ynPriceMap.get(model.getMaterialsNo());
            if (null != ynpv) {
                model.setYnPrice(ynpv.getPrice());
            }
            EnableAndOccupyVO enableAndOccupyVO = warehouseInventoryService.findEnableAndOccupyNum2(model.getMaterialsNo(), searchFilter.getSupplierOrgId(), null, ynInventoryMap);
            if (enableAndOccupyVO != null) {
                model.setIntentionNum(enableAndOccupyVO.getIntentionNum());
                model.setDeliveryNum(enableAndOccupyVO.getDeliveryNum());
                BigDecimal allAmount = enableAndOccupyVO.getEnableNum() == null ? BigDecimal.ZERO : enableAndOccupyVO.getEnableNum();
                BigDecimal occupyAmount = enableAndOccupyVO.getDeliveryNum() == null ? BigDecimal.ZERO : enableAndOccupyVO.getDeliveryNum();
                BigDecimal intentionAmount = enableAndOccupyVO.getIntentionNum() == null ? BigDecimal.ZERO : enableAndOccupyVO.getIntentionNum();
                model.setEnableNum(allAmount.subtract(occupyAmount));
            }

            List<MarketingActivityPriceVO> MarketingActivityDOList = marketingActivityService.activityPriceList(searchFilter.getDealerOrgId(), searchFilter.getOrgId(), model.getMaterialsNo());
            model.setMarketingActivityPriceVOList(MarketingActivityDOList);
            resultLists.add(model);
        }

        result.setPageInfo(new PageInfo(resultList));
        result.setPageInfoList(resultLists);
        return result;
    }


    public ErrorCode remove(List<String> ids, String userId) {
        for (String id : ids) {
            priMaterialsMapper.remove(id, userId);
            try {
                // 删除零件的供应商数据
                materialsSupplierMapper.deleteByMaterialsId(id);
            } catch (Exception e) {
                // 删除零件供应商报错也不能影响零件的删除，没啥影响，所以不作处理
            }
        }
        return ErrorCode.Success;
    }

    public ErrorCode update(MaterialsVO materialsVO) {
        if (priMaterialsMapper.count(materialsVO.getMaterialsNo(), materialsVO.getOrgId()) == 0) {
            return ErrorCode.MaterialsNotExists;
        }
        PriMaterialsDO entity = new PriMaterialsDO();
        BeanUtils.copyProperties(materialsVO, entity);
        rounding(entity);
        if (priMaterialsMapper.update(entity) == 0) {
            return ErrorCode.MaterialsInsertFail;
        }

        //更新零件英文描述
        insertOrUpdateMaterialsLocal(materialsVO,1);

        //主机厂端添加图片同步修改代理商端
        priMaterialsMapper.sysnUpdateImage(entity);

        //先删后增
        materialWarehouseUserMapper.remove(materialsVO.getMaterialsNo(), materialsVO.getOrgId());
        for (MaterialsRelationVO materialsRelationVO : materialsVO.getMaterialsRelationList()) {
            if (StringUtil.isNullOrEmpty(materialsRelationVO.getLocationCode()) || StringUtil.isNullOrEmpty(materialsRelationVO.getUserId())) {
                continue;
            }
            MaterialWarehouseUserDO materialWarehouseUserDO = new MaterialWarehouseUserDO();
            ActionResult<String> id = fastGenClient.textGuid();
            if (id == null || id.getCode() != 0) {
                return ErrorCode.Failure;
            }
            BeanUtils.copyProperties(materialsRelationVO, materialWarehouseUserDO);
            //内部主键
            materialWarehouseUserDO.setId(id.getValue());
            materialWarehouseUserDO.setOrgId(materialsVO.getOrgId());
            materialWarehouseUserDO.setMaterialsNo(materialsVO.getMaterialsNo());
            materialWarehouseUserMapper.insert(materialWarehouseUserDO);
        }

        //isSap=1更新代理商价格
        updateAgentPurPrice(materialsVO);
        return ErrorCode.Success;
    }

    //更新代理商采购单价
    private void updateAgentPurPrice(MaterialsVO materialsVO) {
        String orgId = materialsVO.getOrgId();
        CompanyInfoDO companyInfoDO = companyInfoMapper.item(materialsVO.getOrgId());
        if (null == companyInfoDO || null == companyInfoDO.getIsSap() || 1 != companyInfoDO.getIsSap()) {
            return;
        }
        //更新代理商价格
        //1.通过上游orgId,零件号获取所有代理商零件
        String materialsNo = materialsVO.getMaterialsNo();
        List<PriMaterialsDO> materialsDOList = priMaterialsMapper.listByNo(materialsNo, orgId);
        for (PriMaterialsDO priMaterialsDO : materialsDOList) {
            //更新指导价，代理商基准价
            priMaterialsDO.setAgentPurchasePrice(materialsVO.getPrice());
            //获取代理商目录零售指导价
            priMaterialsDO.setPrice(priMaterialsMapper.getGuidePrice(materialsNo, orgId));
            priMaterialsMapper.update(priMaterialsDO);
        }
    }

    public MaterialsVO item(String materialsId) {
        PriMaterialsDO priMaterialsDO = priMaterialsMapper.item(materialsId);
        if (priMaterialsDO == null) {
            return null;
        }
        MaterialsVO materialsVO = new MaterialsVO();
        BeanUtils.copyProperties(priMaterialsDO, materialsVO);
        newestReplace(materialsVO);
        List<MaterialsRelationVO> viewList = new ArrayList<>();
        PageHelperPlus.orderBy(" ID");
        List<MaterialWarehouseUserDO> list = materialWarehouseUserMapper.findByMaterial(priMaterialsDO.getMaterialsNo(), priMaterialsDO.getOrgId());
        for (MaterialWarehouseUserDO materialWarehouseUserDO : list) {
            MaterialsRelationVO materialsRelationVO = new MaterialsRelationVO();
            BeanUtils.copyProperties(materialWarehouseUserDO, materialsRelationVO);
            viewList.add(materialsRelationVO);
        }
        materialsVO.setMaterialsRelationList(viewList);
        takeDecimals(materialsVO);
        return materialsVO;
    }

    public MaterialsVO itemByNo(String materialsNo, String orgId) {
        PriMaterialsDO priMaterialsDO = priMaterialsMapper.itemByNo(materialsNo, orgId);
        if (priMaterialsDO == null) {
            return null;
        }
        MaterialsVO materialsVO = new MaterialsVO();
        BeanUtils.copyProperties(priMaterialsDO, materialsVO);
        takeDecimals(materialsVO);
        return materialsVO;
    }

    public List<MaterialsVO> itemByNos(List<String> materialsNos, String orgId) {
        List<PriMaterialsDO> priMaterialsDOs = priMaterialsMapper.selectByMaterialsNos(materialsNos, orgId);
        if (CollectionUtils.isEmpty(priMaterialsDOs)){
            return null;
        }
        List<MaterialsVO> voList = BeanUtil.do2bo4List(priMaterialsDOs, MaterialsVO.class);
        voList.forEach(MaterialsService::takeDecimals);
        return voList;
    }


    public void export(List<String> materialsIds) throws Exception {
        List<MaterialsVO> doList = new ArrayList<>();
        for (String materialsId : materialsIds) {
            PriMaterialsDO priMaterialsDO = priMaterialsMapper.item(materialsId);
            MaterialsVO materialsVO = new MaterialsVO();
            BeanUtils.copyProperties(priMaterialsDO, materialsVO);
            if (priMaterialsDO != null) {
                doList.add(materialsVO);
            }
        }
        invokeExport(doList);
    }

    public void download() throws Exception {
        FileUtil.downLoadFile(response, filePath, templateExcelFileName);
    }

    public void exportAll(MaterialsSearchVO condition) throws Exception {
        //PageHelperPlus.startPage(0, 0, "create_date desc");
        if (!StringUtils.isEmpty(condition.getMaterialsNos())) {
            String splitString = ",";
            if (condition.getMaterialsNos().trim().contains("\n")) {
                splitString = "\n";
            }
            String[] str = condition.getMaterialsNos().trim().replace("，", ",").split(splitString);
            condition.setMaterialsList(Arrays.asList((str)));
        }
        if (!StringUtils.isEmpty(condition.getCustomMaterialsNos())) {
            String[] str = condition.getCustomMaterialsNos().trim().replace("，", ",").split(",");
            condition.setCustomMaterialsList(Arrays.asList((str)));
        }
        List<MaterialsVO> doList;
        doList = priMaterialsMapper.listForExport(condition);
        invokeExport(doList);
    }

    private void invokeExport(List<MaterialsVO> doList) throws Exception {
        String title = "零件管理数据导出";
        String[] rowsName = new String[]{"序号", "零件编号", "零件名称", "零件分类", "基本计量单位", "采购组", "进口件", "关键件"};
        List<Object[]> dataList = new ArrayList<Object[]>();
        Object[] objs = null;
        for (int i = 0; i < doList.size(); i++) {
            MaterialsVO e = doList.get(i);
            takeDecimals(e);
            objs = new Object[rowsName.length];
            objs[0] = i + 1;
            objs[1] = e.getMaterialsNo();
            objs[2] = e.getMaterialsDes();
            objs[3] = e.getMaterialsType();
            objs[4] = e.getUnit();
            objs[5] = e.getPurchaseGroup();
            objs[6] = e.getEntranceDevice() == 1 ? "是" : "否";
            objs[7] = e.getCrucialDevice() == 1 ? "是" : "否";
            dataList.add(objs);
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);
    }

    public FunctionResult<String> importExcel(InputStream in, String fileName, String orgId, String userId) throws Exception {
        FunctionResult result = new FunctionResult();
        // 获取解析excel的wb
        HSSFWorkbook wb = new HSSFWorkbook(in);
        //获取第一张sheet
        HSSFSheet sheet = wb.getSheetAt(0);
        //获取总行数
        int totalRow = sheet.getLastRowNum();
        if (totalRow < 2) {
            result.setCode(ErrorCode.ImportExcelError);
            result.setValue(ErrorCode.ImportExcelError.getDesc());
            return result;
        }
        //获取总列数
        int totalCell = sheet.getRow(1).getLastCellNum();
        if (totalCell != 11) {
            result.setCode(ErrorCode.ImportExcelError);
            result.setValue(ErrorCode.ImportExcelError.getDesc());
            return result;
        }
        List<PriMaterialsDO> excelList = new ArrayList<>();
        List<PubMaterialsDO> pubMaterialsDOS = new ArrayList<>();
        boolean partSuccess = false;
        //获取导入数据列表

        for (int i = 2; i <= totalRow; i++) {
            HSSFRow curRow = sheet.getRow(i);
            if (curRow == null) {
                continue;
            }
            if (isRowEmpty(curRow)) {
                continue;
            }
            PriMaterialsDO entity = new PriMaterialsDO();
            DecimalFormat df = new DecimalFormat("0");
            curRow.getCell(1).setCellType(CellType.STRING);
            curRow.getCell(3).setCellType(CellType.STRING);
            String ce = curRow.getCell(1).toString();

            //零件编码
            String materialsNo = curRow.getCell(1) == null ? "" : ce;
            //零件名称
            String materialsDes = curRow.getCell(2) == null ? "" : ExcelUtil.getCellStringValue(curRow.getCell(2));
            //零件分类编码
            String materialsTypeId = curRow.getCell(3) == null ? "" : (ExcelUtil.getCellStringValue(curRow.getCell(3))).replace(".0", "");
            //计量单位
            String unit = curRow.getCell(4) == null ? "" : ExcelUtil.getCellStringValue(curRow.getCell(4));
            //销售价格
            String price = curRow.getCell(5) == null ? "" : ExcelUtil.getCellStringValue(curRow.getCell(5));
            //是否进口件
            String entranceDevice = curRow.getCell(6) == null ? "" : ExcelUtil.getCellStringValue(curRow.getCell(6));
            //是否关键件
            String crucialDevice = curRow.getCell(7) == null ? "" : ExcelUtil.getCellStringValue(curRow.getCell(7));
            //零件尺寸
            String materialsMeasure = curRow.getCell(8) == null ? "" : ExcelUtil.getCellStringValue(curRow.getCell(8));
            //零件英文描述
            String materialsDesEn = curRow.getCell(9) == null ? "" : ExcelUtil.getCellStringValue(curRow.getCell(9));
            //是自制件：0-否，1-是
            String selfMadeStr = curRow.getCell(10) == null ? "" : ExcelUtil.getCellStringValue(curRow.getCell(10));
            PubMaterialsDO pubMaterialsDO = new PubMaterialsDO();
            pubMaterialsDO.setMaterialsNo(materialsNo);
            pubMaterialsDO.setMaterialsDesEn(materialsDesEn);
            pubMaterialsDO.setCreateId(userId);
            pubMaterialsDO.setCreateDate(new Date());
            pubMaterialsDOS.add(pubMaterialsDO);
            entity.setOrgId(orgId);
            entity.setCreateId(userId);
            entity.setMaterialsNo(materialsNo);
            entity.setMaterialsDes(materialsDes);
            entity.setMaterialsTypeId(materialsTypeId);
            entity.setUnit(unit);
            entity.setMaterialsMeasure(materialsMeasure);
            entity.setErrorRow(i + 1);
            if (!isNumber(price)) {
                price = "-1";
            }
            entity.setPrice(new BigDecimal(price).multiply(new BigDecimal(100)));

            if (!isNumber(entranceDevice)) {
                entranceDevice = "-1";
            }
            entity.setEntranceDevice(getShort(entranceDevice));

            if (!isNumber(crucialDevice)) {
                crucialDevice = "-1";
            }
            entity.setCrucialDevice(getShort(crucialDevice));
            if (StringUtils.isBlank(selfMadeStr)) {
                selfMadeStr = "0";
            }
            entity.setSelfMade(CommonUtils.tryParseInt(selfMadeStr));
            excelList.add(entity);
        }

        if (excelList.isEmpty()) {
            result.setCode(ErrorCode.ImportExcelNoData);
            result.setValue(ErrorCode.ImportExcelNoData.getDesc());
        }
        //定义错误数据返回列表
        List<PriMaterialsDO> errorList = new ArrayList<>();
        for (PriMaterialsDO entity : excelList) {
            if (StringUtils.isBlank(entity.getMaterialsNo())) {
                entity.setRemark("零件编号不能为空");
                errorList.add(entity);
                continue;
            }
            if (isContainChinese(entity.getMaterialsNo())) {
                entity.setRemark("零件编号只能为数字、字母");
                errorList.add(entity);
                continue;
            }
            if (entity.getMaterialsNo().length() > 20) {
                entity.setRemark("零件编号超长，请控制在20位字母加数字以内");
                errorList.add(entity);
                continue;
            }
            if (priMaterialsMapper.count(entity.getMaterialsNo(), orgId) > 0) {
                entity.setRemark("零件编号已存在");
                errorList.add(entity);
                continue;
            }
            if (StringUtils.isBlank(entity.getMaterialsDes())) {
                entity.setRemark("零件名称不能为空");
                errorList.add(entity);
                continue;
            }
            if (entity.getMaterialsDes().length() > 50) {
                entity.setRemark("零件名称超长，请控制在50个字符以内");
                errorList.add(entity);
                continue;
            }
            if (StringUtils.isBlank(entity.getMaterialsTypeId())) {
                entity.setRemark("零件分类编码格式不正确");
                errorList.add(entity);
                continue;
            }
            if (!CommonUtils.validateIntegerInCollection(entity.getSelfMade(), Arrays.asList(0, 1))) {
                entity.setRemark("是否自制件信息填写不正确");
                errorList.add(entity);
                continue;
            }
            MaterialClassDO materialClassDOs = new MaterialClassDO();
            materialClassDOs.setOrgId(orgId);
            materialClassDOs.setClassCode(entity.getMaterialsTypeId());
            Integer countClass = materialClassMapper.classCodeCount(materialClassDOs);
            if (countClass > 1) {
                entity.setRemark("零件分类编码存在多条数据");
                errorList.add(entity);
                continue;
            }
            MaterialClassDO materialClassDO = materialClassMapper.itemByCode(entity.getMaterialsTypeId(), orgId);
            if (materialClassDO == null) {
                entity.setRemark("零件分类不存在");
                errorList.add(entity);
                continue;
            }
            //零件分类名称
            entity.setMaterialsTypeId(materialClassDO.getId());
            entity.setMaterialsType(materialClassDO.getMaterialCalssName());
            if (StringUtils.isBlank(entity.getUnit())) {
                entity.setRemark("基本计量单位不能为空");
                errorList.add(entity);
                continue;
            }
            if (entity.getUnit().length() > 10) {
                entity.setRemark("基本计量单位过长，不要超过10个字符");
                errorList.add(entity);
                continue;
            }
            if (entity.getEntranceDevice() == -1) {
                entity.setRemark("进口件格式不正确");
                errorList.add(entity);
                continue;
            }
            if (entity.getCrucialDevice() == -1) {
                entity.setRemark("关键件格式不正确");
                errorList.add(entity);
                continue;
            }
            if (entity.getPrice().compareTo(new BigDecimal(1)) == -1) {
                entity.setRemark("销售价格不能为空或负数");
                errorList.add(entity);
                continue;
            }
            //执行insert操作
            if (priMaterialsMapper.insert(entity) == 0) {
                //取整
                entity.setPrice(entity.getPrice().multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP));
                entity.setRemark("新增数据失败");
                errorList.add(entity);
                continue;
            }
            partSuccess = true;
        }
        //导入英文描述
        for (PubMaterialsDO pubMaterialsDO : pubMaterialsDOS) {
            insertOrUpdateMaterialsLocal(pubMaterialsDO, 1);
        }
        //返回错误list（将错误文件流写入内存导出错误文件,方案待考察）
        if (!errorList.isEmpty()) {
            /*invokeErrExport(errorList);*/
            result.setCode(ErrorCode.Success);
            if (!partSuccess) {
                result.setCode(ErrorCode.Failure);
            }
            result.setValue(errorList);
            return result;
        }
        result.setCode(ErrorCode.Success);
        result.setValue(new ArrayList<>());
        return result;
    }


    public static boolean isRowEmpty(HSSFRow row) {
        for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
            HSSFCell cell = row.getCell(c);
            if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK && !StringUtil.isNullOrSpace(ExcelUtil.getCellStringValue(cell))) {
                return false;
            }
        }
        return true;
    }

    public static Pattern CHINESE_PATTERN = Pattern.compile("[\u4e00-\u9fa5]");

    public static boolean isContainChinese(String str) {
        Matcher m = CHINESE_PATTERN.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    private static boolean isNumber(String str) {
        if (str == null) {
            return false;
        }
        String reg = "-?[0-9]+.?[0-9]+";
        String regAct = "^-?\\d+(\\.\\d+)?(E-?\\d+)?$";
        return str.matches(reg) || str.matches(regAct);
    }

    private static Short getShort(String input) {
        BigDecimal bigDecimal = new BigDecimal(input).setScale(0, BigDecimal.ROUND_DOWN);
        if (bigDecimal.compareTo(new BigDecimal(1)) >= 0) {
            return new Short("1");
        } else {
            return new Short("0");
        }
    }

    public FunctionResult importMaterialWeight(MultipartFile file, String orgId) throws Exception{
        FunctionResult result = new FunctionResult();
        Workbook wb = null;//同时兼容Excel-2003及Excel-2007
        try {
            InputStream in = file.getInputStream();
            wb = new HSSFWorkbook(in);
        } catch (Exception ex) {
            InputStream in = file.getInputStream();
            wb = new XSSFWorkbook(in);
        }
        Sheet sheet = wb.getSheetAt(0);
        int totalRow = sheet.getLastRowNum();
        if (totalRow < 2) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        int totalCell = sheet.getRow(1).getLastCellNum();
        if (totalCell != 3) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        List<MaterialWeightImportVO> errorDetailVOList = new ArrayList<>();
        for(int i = 2 ; i < totalRow + 1 ; i++){
            Row curRow = sheet.getRow(i);
            String materialsNo = getCellValue(curRow, 1);
            String weightStr = getCellValue(curRow, 2);
            if(StringUtils.isEmpty(materialsNo)){
                MaterialWeightImportVO errorImport = new MaterialWeightImportVO();
                errorImport.setErrorRow(i + 1);
                errorImport.setRemark("零件编码不能为空");
                errorDetailVOList.add(errorImport);
                continue;
            }
            if(StringUtils.isEmpty(weightStr)){
                MaterialWeightImportVO errorImport = new MaterialWeightImportVO();
                errorImport.setErrorRow(i + 1);
                errorImport.setRemark("重量值不能为空");
                errorDetailVOList.add(errorImport);
                continue;
            }
            BigDecimal weight;
            try{
                weight = new BigDecimal(weightStr);
            }catch (Exception e){
                MaterialWeightImportVO errorImport = new MaterialWeightImportVO();
                errorImport.setErrorRow(i + 1);
                errorImport.setRemark("重量值格式不正确");
                errorDetailVOList.add(errorImport);
                continue;
            }

            String[] split = weightStr.split(".");
            if(split.length == 2 && split[1].length()>4){
                MaterialWeightImportVO errorImport = new MaterialWeightImportVO();
                errorImport.setErrorRow(i + 1);
                errorImport.setRemark("重量值保留小数点后四位");
                errorDetailVOList.add(errorImport);
                continue;
            }
            //查询零件是否存在
            PriMaterialsDO priMaterialsDO = priMaterialsMapper.itemByNo(materialsNo, orgId);
            if (priMaterialsDO == null) {
                MaterialWeightImportVO errorImport = new MaterialWeightImportVO();
                errorImport.setErrorRow(i + 1);
                errorImport.setRemark("零件编码不存在");
                errorDetailVOList.add(errorImport);
                continue;
            }
            PriMaterialsDO updatePriMaterial = new PriMaterialsDO();
            updatePriMaterial.setMaterialsId(priMaterialsDO.getMaterialsId());
            updatePriMaterial.setWeight(weight);
            updatePriMaterial.setWeightUnit("KG");
            boolean updateSuccess = priMaterialsMapper.update(updatePriMaterial) > 0;
            if(!updateSuccess){
                MaterialWeightImportVO errorImport = new MaterialWeightImportVO();
                errorImport.setErrorRow(i + 1);
                errorImport.setRemark("更新数据库失败");
                errorDetailVOList.add(errorImport);
                continue;
            }
        }

        if (ListUtil.isNullOrEmpty(errorDetailVOList)) {
            result.setValue(new ArrayList<>());
            result.setCode(ErrorCode.Success);
        } else {
            result.setValue(errorDetailVOList);
            result.setCode(ErrorCode.IllegalArument);
        }
        return result;

    }


    public FunctionResult importLocationExcel(MultipartFile file, String orgId, String userId) throws Exception {
        FunctionResult result = new FunctionResult();
        //Workbook wb = WorkbookFactory.create(in);
        Workbook wb = null;//同时兼容Excel-2003及Excel-2007
        try {
            InputStream in = file.getInputStream();
            wb = new HSSFWorkbook(in);
        } catch (Exception ex) {
            // 解决read error异常
            // in = new FileInputStream(file);
            InputStream in = file.getInputStream();
            wb = new XSSFWorkbook(in);
        }
        Sheet sheet = wb.getSheetAt(0);
        int totalRow = sheet.getLastRowNum();
        if (totalRow < 2) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        int totalCell = sheet.getRow(1).getLastCellNum();
        if (totalCell != 3) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        List<MaterialsSearchVO> errorDetailVOList = new ArrayList<>();
        MaterialLocationRelationDO relationDO;
        String warehouseCode;
        String areaCode;
        ActionResult<String> id;
        boolean success;
        for (int i = 2; i <= totalRow; i++) {
            //HSSFRow curRow=sheet.getRow(i);
            Row curRow = sheet.getRow(i);
            MaterialsSearchVO detailVO = new MaterialsSearchVO();
            if (curRow == null) {
                continue;
            }
            String no = getCellValue(curRow, 0);
            String materialsNo = getCellValue(curRow, 1);
            String locationCode = getCellValue(curRow, 2);
            if (StringUtil.isNullOrEmpty(materialsNo) && StringUtil.isNullOrEmpty(locationCode)) {
                break;
            }
            if (StringUtil.isNullOrEmpty(materialsNo)) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("零件编码不能为空");
                errorDetailVOList.add(detailVO);
                continue;
            }
            if (StringUtil.isNullOrEmpty(locationCode)) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("库存储位不能为空");
                errorDetailVOList.add(detailVO);
                continue;
            }
            materialsNo = materialsNo.trim();
            locationCode = locationCode.trim();
            if (locationCode.length() > 64) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("库存储位长度不能大于64位");
                errorDetailVOList.add(detailVO);
                continue;
            }
            PriMaterialsDO priMaterialsDO = priMaterialsMapper.itemByNo(materialsNo, orgId);
            if (priMaterialsDO == null) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("零件不存在");
                errorDetailVOList.add(detailVO);
                continue;
            }
            WarehouseAreaLocationDO warehouseAreaLocationDO = warehouseAreaLocationDOMapper.item(locationCode,orgId);
            if (warehouseAreaLocationDO == null) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("储位不存在");
                errorDetailVOList.add(detailVO);
                continue;
            }

            Map<String, Object> warehouseMap = warehouseAreaLocationDOMapper.findAllCode(locationCode, orgId);
            if (warehouseMap == null || warehouseMap.get("WAREHOUSE_CODE") == null || warehouseMap.get("AREA_CODE") == null) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("库区不存在");
                errorDetailVOList.add(detailVO);
                continue;
            }
            priMaterialsDO.setStockLocation(locationCode);
            success = priMaterialsMapper.update(priMaterialsDO) > 0;
            if (!success) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("更新库存储位失败");
                errorDetailVOList.add(detailVO);
                continue;
            }
            areaCode = (String) warehouseMap.get("AREA_CODE");
            warehouseCode = (String) warehouseMap.get("WAREHOUSE_CODE");
            relationDO = materialLocationRelationMapper.findByAreaCode(materialsNo, warehouseCode, orgId);
            if (relationDO == null) {
                relationDO = new MaterialLocationRelationDO();
                id = fastGenClient.textGuid();
                if (id == null || id.getCode() != 0) {
                    detailVO.setErrorRow(i + 1);
                    detailVO.setRemark("新增零件储位失败");
                    errorDetailVOList.add(detailVO);
                    continue;
                }
                relationDO.setId(fastGenClient.textGuid().getValue());
                relationDO.setMaterialNo(materialsNo);
                relationDO.setWarehouseCode(warehouseCode);
                relationDO.setAreaCode(areaCode);
                relationDO.setLocationCode(locationCode);
                relationDO.setOrgId(orgId);
                relationDO.setCreateDate(new Date());
                relationDO.setCreateId(userId);
                relationDO.setCreateName(commonService.getUserName(userId));
                success = materialLocationRelationMapper.insert(relationDO) > 0;
                if (!success) {
                    detailVO.setErrorRow(i + 1);
                    detailVO.setRemark("新增零件储位失败");
                    errorDetailVOList.add(detailVO);
                }
            } else {
                if (!locationCode.equals(relationDO.getLocationCode())) {
                    relationDO.setLocationCode(locationCode);
                    relationDO.setAreaCode(areaCode);
                    relationDO.setWarehouseCode(warehouseCode);
                    success = materialLocationRelationMapper.updateByPrimaryKey(relationDO) > 0;
                    if (!success) {
                        detailVO.setErrorRow(i + 1);
                        detailVO.setRemark("更新零件储位失败");
                        errorDetailVOList.add(detailVO);
                    }
                }

            }
        }

        if (ListUtil.isNullOrEmpty(errorDetailVOList)) {
            result.setValue(new ArrayList<>());
            result.setCode(ErrorCode.Success);
        } else {
            result.setValue(errorDetailVOList);
            result.setCode(ErrorCode.IllegalArument);
        }
        return result;
    }

    private String getCellValue(Row curRow, int i) {
        String value = "";
        if (curRow.getCell(i) != null) {
            curRow.getCell(i).setCellType(CellType.STRING);
            value = curRow.getCell(i).getStringCellValue();
        }
        return value;
    }

    public void downloadLocationExcel() throws Exception {
        FileUtil.downLoadFile(response, filePath, templateLocationExcelFileName);
    }
    
    public void getAuthDeviceTemplate() throws Exception {
        FileUtil.downLoadFile(response, filePath, templateAuthExcelFileName);
    }

    public void downloadTyprEntranceCrucialExcel() throws Exception {
        FileUtil.downLoadFile(response, filePath, templateTyprEntranceCrucial);
    }

    /**
     * @Author: WangKe
     * @Description: 查询零件编码关系列表
     * @Date: 2018/5/7 0007
     */
    public PageCommonVO<MaterialLocationRelationVO> locationRelationList(SearchCommonVO<MaterialLocationRelationVO> condition) {
        PageHelperPlus.orderBy("create_date desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        PageCommonVO result = new PageCommonVO();
        List<MaterialLocationRelationVO> voList = materialLocationRelationMapper.list(condition.getFilters());
        result.setPageInfo(new PageInfo(voList));
        return result;
    }

    public FunctionResult<String> importReplace(MultipartFile file, String orgId) throws IOException {
        FunctionResult result = new FunctionResult();
        Workbook wb;//同时兼容Excel-2003及Excel-2007
        try {
            InputStream in = file.getInputStream();
            wb = new HSSFWorkbook(in);
        } catch (Exception ex) {
            InputStream in = file.getInputStream();
            wb = new XSSFWorkbook(in);
        }
        Sheet sheet = wb.getSheetAt(0);
        int totalRow = sheet.getLastRowNum();
        if (totalRow < 2) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        int totalCell = sheet.getRow(1).getLastCellNum();
        if (totalCell != 8) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        List<MaterialsSearchVO> errorDetailVOList = new ArrayList<>();
        boolean success;
        for (int i = 2; i <= totalRow; i++) {
            Row curRow = sheet.getRow(i);
            MaterialsSearchVO detailVO = new MaterialsSearchVO();
            if (curRow == null) {
                continue;
            }
            ImportReplaceVO entity = new ImportReplaceVO();

            String no = getCellValue(curRow, 0);//序号
            String materialsNo = getCellValue(curRow, 1);//零件编码
            String replaceMaterialsNote = getCellValue(curRow, 3);//改型零件编码
            String replaceMaterialsNo = getCellValue(curRow, 4);//替代零件编码
            String remark = getCellValue(curRow, 6);//备注
            String del = getCellValue(curRow, 7);//是否删除 0: 否，1: 是

            if (StringUtil.isNullOrEmpty(replaceMaterialsNo) && StringUtil.isNullOrEmpty(materialsNo) && StringUtil.isNullOrEmpty(replaceMaterialsNote)) {
                continue;
            }
            if (StringUtil.isNullOrEmpty(materialsNo)) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("零件编码不能为空");
                errorDetailVOList.add(detailVO);
                continue;
            }
            if (materialsNo.equals(replaceMaterialsNo)) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("零件编码不能和替代零件编码一样");
                errorDetailVOList.add(detailVO);
                continue;
            }
            materialsNo = materialsNo.trim();
            PriMaterialsDO priMaterialsDO = priMaterialsMapper.itemByNoOrgId(materialsNo, orgId);
            if (priMaterialsDO == null) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("零件不存在");
                errorDetailVOList.add(detailVO);
                continue;
            }

            boolean needDel = (StringUtils.isNotBlank(del) && "1".equals(del));
            if (needDel) {//清空零件的替换零件
                priMaterialsMapper.clearReplaceMaterialsByNoOrgId(materialsNo, orgId);
                continue;
            }

            entity.setMaterialsId(priMaterialsDO.getMaterialsId());
            if (StringUtil.isNullOrEmpty(replaceMaterialsNo)) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("替代零件编号不能为空");
                errorDetailVOList.add(detailVO);
                continue;
            }

            replaceMaterialsNo = replaceMaterialsNo.trim();
            String tempReplaceMaterialsNo = replaceMaterialsNo.replaceAll("，", ",");
            if (StringUtils.isNotBlank(tempReplaceMaterialsNo)) {
                List<String> resultRepMaterNo = new ArrayList<>();
                String[] repMaterNo = tempReplaceMaterialsNo.split(",");
                StringBuilder existErrRemark = new StringBuilder();
                for (String aRepMaterNo : repMaterNo) {
                    PriMaterialsDO replacePriMaterialsDO = priMaterialsMapper.itemByNoOrgId(aRepMaterNo, orgId);
                    if (replacePriMaterialsDO == null) {
                        existErrRemark.append(aRepMaterNo).append(",");
                    }

                    resultRepMaterNo.add(aRepMaterNo);
                }

                if (existErrRemark.length() > 0) {
                    detailVO.setRemark("替换零件" + existErrRemark.deleteCharAt(existErrRemark.length() - 1) + "不存在");
                    detailVO.setErrorRow(i + 1);
                    errorDetailVOList.add(detailVO);
                    continue;
                }

                entity.setReplaceMaterialsNo(StringUtils.join(resultRepMaterNo, ","));
            }

            if (!StringUtil.isNullOrEmpty(replaceMaterialsNote)) {
                entity.setReplaceMaterialsNote(replaceMaterialsNote.trim());
            }
            entity.setOrgId(orgId);
            entity.setRemark(remark);
            success = priMaterialsMapper.replaceUpdate(entity) > 0;
            if (!success) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("更新失败");
                errorDetailVOList.add(detailVO);
            }
        }
        if (ListUtil.isNullOrEmpty(errorDetailVOList)) {
            result.setValue(new ArrayList<>());
            result.setCode(ErrorCode.Success);
        } else {
            result.setValue(errorDetailVOList);
            result.setCode(ErrorCode.IllegalArument);
        }
        return result;
    }

    public FunctionResult<String> importTyprEntranceCruciaLExcel(MultipartFile file, String orgId) throws IOException {
        FunctionResult result = new FunctionResult();
        Workbook wb = null;//同时兼容Excel-2003及Excel-2007
        try {
            InputStream in = file.getInputStream();
            wb = new HSSFWorkbook(in);
        } catch (Exception ex) {
            // 解决read error异常
            // in = new FileInputStream(file);
            InputStream in = file.getInputStream();
            wb = new XSSFWorkbook(in);
        }
        Sheet sheet = wb.getSheetAt(0);
        int totalRow = sheet.getLastRowNum();
        if (totalRow < 2) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        int totalCell = sheet.getRow(1).getLastCellNum();
        if (totalCell != 6) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        List<MaterialsSearchVO> errorDetailVOList = new ArrayList<>();
        boolean success;
        for (int i = 2; i <= totalRow; i++) {
            Row curRow = sheet.getRow(i);
            MaterialsSearchVO detailVO = new MaterialsSearchVO();
            if (curRow == null) {
                continue;
            }
            PriMaterialsDO entity = new PriMaterialsDO();

            String no = getCellValue(curRow, 0);
            String materialsNo = getCellValue(curRow, 1);//零件编号
            String materialsTypeId = getCellValue(curRow, 2);//零件分类id
            String entranceDevice = getCellValue(curRow, 3);//进口件
            String crucialDevice = getCellValue(curRow, 4);//关键件
            String maintenanceType = getCellValue(curRow, 5).trim();//A/B件
            if (StringUtil.isNullOrEmpty(materialsNo) && (StringUtil.isNullOrEmpty(materialsTypeId) || StringUtil.isNullOrEmpty(entranceDevice) || StringUtil.isNullOrEmpty(crucialDevice))) {
                break;
            }
            if (StringUtil.isNullOrEmpty(materialsNo)) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("零件编码不能为空");
                errorDetailVOList.add(detailVO);
                continue;
            }
//            if (StringUtil.isNullOrEmpty(materialsTypeId)) {
//                detailVO.setErrorRow(i + 1);
//                detailVO.setRemark("零件分类编码不能为空");
//                errorDetailVOList.add(detailVO);
//                continue;
//            }
//            if (StringUtil.isNullOrEmpty(entranceDevice)) {
//                detailVO.setErrorRow(i + 1);
//                detailVO.setRemark("进口件不能为空");
//                errorDetailVOList.add(detailVO);
//                continue;
//            }
//            if (StringUtil.isNullOrEmpty(crucialDevice)) {
//                detailVO.setErrorRow(i + 1);
//                detailVO.setRemark("关键件不能为空");
//                errorDetailVOList.add(detailVO);
//                continue;
//            }
            materialsNo = materialsNo.trim();
            entity.setMaterialsNo(materialsNo);

            PriMaterialsDO priMaterialsDO = priMaterialsMapper.itemByNo(materialsNo, orgId);
            if (priMaterialsDO == null) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("零件不存在");
                errorDetailVOList.add(detailVO);
                continue;
            }
            entity.setMaterialsId(priMaterialsDO.getMaterialsId());

            //校验零件分类
            if ( StringUtils.isNotEmpty(materialsTypeId)) {
                materialsTypeId = materialsTypeId.trim();
                MaterialClassDO materialClassDO = materialClassMapper.itemByCode(materialsTypeId, orgId);
                if (materialClassDO == null) {
                    detailVO.setErrorRow(i + 1);
                    detailVO.setRemark("零件分类不存在");
                    errorDetailVOList.add(detailVO);
                    continue;
                }
                entity.setMaterialsTypeId(materialClassDO.getId());
                entity.setMaterialsType(materialClassDO.getMaterialCalssName());
            }

            //校验进口件格式
            if (StringUtils.isNotEmpty(entranceDevice)) {
                entranceDevice = entranceDevice.trim();
//                if (!isNumber(entranceDevice)) {
//                    detailVO.setErrorRow(i + 1);
//                    detailVO.setRemark("是否进口件格式不正确");
//                    errorDetailVOList.add(detailVO);
//                    continue;
//                }
                if (Integer.valueOf(entranceDevice) != 0 && Integer.valueOf(entranceDevice) != 1) {
                    detailVO.setErrorRow(i + 1);
                    detailVO.setRemark("是否进口件数据不正确");
                    errorDetailVOList.add(detailVO);
                    continue;
                }

                entity.setEntranceDevice(getShort(entranceDevice));
            }

            //校验关键件格式
            if (StringUtils.isNotEmpty(crucialDevice)) {
                crucialDevice = crucialDevice.trim();
//                if (!isNumber(crucialDevice)) {
//                    detailVO.setErrorRow(i + 1);
//                    detailVO.setRemark("是否关键件格式不正确");
//                    errorDetailVOList.add(detailVO);
//                    continue;
//                }
                if (Integer.valueOf(crucialDevice) != 0 && Integer.valueOf(crucialDevice) != 1) {
                    detailVO.setErrorRow(i + 1);
                    detailVO.setRemark("是否关键件数据不正确");
                    errorDetailVOList.add(detailVO);
                    continue;
                }

                entity.setCrucialDevice(getShort(crucialDevice));
            }

            //校验AB件格式
            if (StringUtils.isNotEmpty(maintenanceType)){
                if (!"A".equals(maintenanceType) && !"B".equals(maintenanceType)) {
                    detailVO.setErrorRow(i + 1);
                    detailVO.setRemark("A/B件数据不正确");
                    errorDetailVOList.add(detailVO);
                    continue;
                }
                entity.setMaintenanceType(maintenanceType);
            }

            success = priMaterialsMapper.update(entity) > 0;
            if (!success) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("更新失败");
                errorDetailVOList.add(detailVO);
            }
        }
        if (ListUtil.isNullOrEmpty(errorDetailVOList)) {
            result.setValue(new ArrayList<>());
            result.setCode(ErrorCode.Success);
        } else {
            result.setValue(errorDetailVOList);
            result.setCode(ErrorCode.IllegalArument);
        }
        return result;

    }

    public void downloadReplace() throws Exception {
        FileUtil.downLoadFile(response, filePath, templateReplace);
    }

    public FunctionResult<String> importKeeper(MultipartFile file, String orgId) throws IOException {
        FunctionResult result = new FunctionResult();
        Workbook wb = null;//同时兼容Excel-2003及Excel-2007
        try {
            InputStream in = file.getInputStream();
            wb = new HSSFWorkbook(in);
        } catch (Exception ex) {
            // 解决read error异常
            // in = new FileInputStream(file);
            InputStream in = file.getInputStream();
            wb = new XSSFWorkbook(in);
        }
        Sheet sheet = wb.getSheetAt(0);
        int totalRow = sheet.getLastRowNum();
        if (totalRow < 2) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        int totalCell = sheet.getRow(1).getLastCellNum();
        if (totalCell != 5) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        List<MaterialsSearchVO> errorDetailVOList = new ArrayList<>();
        Map<String, Map<String, String>> infoMap = new HashMap<>(32);
        Map<String, String> detailMap;
        WarehouseDO warehouseDO;
        WarehouseAreaDO areaDO;
        String shelfNo;
        String keeperId;
        for (int i = 2; i <= totalRow; i++) {
            Row curRow = sheet.getRow(i);
            MaterialsSearchVO detailVO = new MaterialsSearchVO();
            if (curRow == null) {
                continue;
            }

            String materialsNo = getCellValue(curRow, 1);
            String warehouseCode = getCellValue(curRow, 2);
            String areaCode = getCellValue(curRow, 3);
            String keeper = getCellValue(curRow, 4);
            if (StringUtil.isNullOrEmpty(materialsNo) && (StringUtil.isNullOrEmpty(warehouseCode) || StringUtil.isNullOrEmpty(areaCode) || StringUtil.isNullOrEmpty(keeper))) {
                break;
            }
            if (StringUtil.isNullOrEmpty(materialsNo)) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("零件编码不能为空");
                errorDetailVOList.add(detailVO);
                continue;
            }
            if (StringUtil.isNullOrEmpty(warehouseCode)) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("仓库编码不能为空");
                errorDetailVOList.add(detailVO);
                continue;
            }
            if (StringUtil.isNullOrEmpty(areaCode)) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("库区编码不能为空");
                errorDetailVOList.add(detailVO);
                continue;
            }
            if (StringUtil.isNullOrEmpty(keeper)) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("保管员不能为空");
                errorDetailVOList.add(detailVO);
                continue;
            }
            detailMap = infoMap.get(materialsNo + "_" + warehouseCode + "-" + areaCode);
            if (detailMap == null) {
                detailMap = new HashMap<>(32);
                warehouseDO = warehouseDOMapper.itemByWarehouseCode(orgId, warehouseCode);
                if (warehouseDO == null) {
                    detailVO.setErrorRow(i + 1);
                    detailVO.setRemark("未找到此仓库，" + warehouseCode);
                    errorDetailVOList.add(detailVO);
                    continue;
                }
                detailMap.put("warehouseId", warehouseDO.getId());
                areaDO = warehouseAreaDOMapper.itemByCode(orgId, areaCode, warehouseDO.getId());
                if (areaDO == null) {
                    detailVO.setErrorRow(i + 1);
                    detailVO.setRemark("未找到此库区，" + areaCode);
                    errorDetailVOList.add(detailVO);
                    continue;
                }
                detailMap.put("areaId", areaDO.getId());
                shelfNo = warehouseAreaLocationDOMapper.findShelfNo(areaDO.getId(), orgId);
                if (StringUtil.isNullOrEmpty(shelfNo)) {
                    detailVO.setErrorRow(i + 1);
                    detailVO.setRemark(areaCode + "此库区下未找到货架编码");
                    errorDetailVOList.add(detailVO);
                    continue;
                }
                detailMap.put("shelfNo", shelfNo);
                keeperId = warehouseAreaLocationDOMapper.findkeeperId(keeper, orgId);
                if (StringUtil.isNullOrEmpty(keeperId)) {
                    detailVO.setErrorRow(i + 1);
                    detailVO.setRemark("此保管员不存在，" + keeper);
                    errorDetailVOList.add(detailVO);
                    continue;
                }
                detailMap.put("keeperId", keeperId);
                infoMap.put(materialsNo + "_" + warehouseCode + "-" + areaCode, detailMap);
            }
            MaterialWarehouseUserDO warehouseUserDO = new MaterialWarehouseUserDO();
            warehouseUserDO.setMaterialsNo(materialsNo);
            warehouseUserDO.setOrgId(orgId);
            warehouseUserDO.setWarehouseCode(warehouseCode);
            warehouseUserDO.setAreaCode(areaCode);
            List<MaterialWarehouseUserDO> warehouseUserDOList = materialWarehouseUserMapper.list(warehouseUserDO);
            if (!ListUtil.isNullOrEmpty(warehouseUserDOList)) {
                warehouseUserDO = warehouseUserDOList.get(0);
                warehouseUserDO.setUserId(detailMap.get("keeperId"));
                warehouseUserDO.setUserName(keeper);
                materialWarehouseUserMapper.updateByPrimaryKey(warehouseUserDO);
            } else {
                warehouseUserDO.setId(fastGenClient.textGuid().getValue());
                warehouseUserDO.setWarehouseId(detailMap.get("warehouseId"));
                warehouseUserDO.setAreaId(detailMap.get("areaId"));
                warehouseUserDO.setUserId(detailMap.get("keeperId"));
                warehouseUserDO.setUserName(keeper);
                warehouseUserDO.setLocationCode(detailMap.get("shelfNo"));
                materialWarehouseUserMapper.insert(warehouseUserDO);
            }
        }
        if (ListUtil.isNullOrEmpty(errorDetailVOList)) {
            result.setValue(new ArrayList<>());
            result.setCode(ErrorCode.Success);
        } else {
            result.setValue(errorDetailVOList);
            result.setCode(ErrorCode.IllegalArument);
        }
        return result;
    }

    public void downloadKeeper() throws Exception {
        FileUtil.downLoadFile(response, filePath, templateKeeper);
    }

    public boolean saveByInbound(String materialsNo, String orgId, String supplierOrgId) throws Exception {
        PriMaterialsDO priMaterialsDO = priMaterialsMapper.itemByNo(materialsNo, orgId);
        if (priMaterialsDO != null) {
            return true;
        }
        PriMaterialsDO newPriMaterialsDO = priMaterialsMapper.itemByNo(materialsNo, supplierOrgId);
        if (newPriMaterialsDO == null) {
            throw new Exception("供应商基础零件中未找到此零件，" + materialsNo);
        }
        priMaterialsDO = new PriMaterialsDO();
        BeanUtils.copyProperties(newPriMaterialsDO, priMaterialsDO);
        priMaterialsDO.setStockLocation(null);
        priMaterialsDO.setOrgId(orgId);
        priMaterialsDO.setStandardPrice(new BigDecimal("0"));
        priMaterialsDO.setPrice(new BigDecimal("0"));
        //判断是否进出口
        /**
        CompanyInfoVO companyInfoVO = companyInfoService.info(orgId);
        if (StringUtils.isNotEmpty(companyInfoVO.getSapCode()) && CompanyUtil.JCK_SAP_CODE.equals(companyInfoVO.getSapCode())){
            MaterialsSearchVO searchVO = new MaterialsSearchVO();
            searchVO.setOrgId(orgId);
            searchVO.setMaterialsNos(materialsNo);
            BigDecimal maxStandardPrice = priMaterialsMapper.getMaxPrice(searchVO);
            priMaterialsDO.setStandardPrice(maxStandardPrice);
        }
        */
        priMaterialsDO.setIsDirectCast(0);
        priMaterialsDO.setIsDirectCastHF(0);
        priMaterialsDO.setBasicMachine(0);
        priMaterialsDO.setSelfMade(0);

        boolean success = priMaterialsMapper.insert(priMaterialsDO) > 0;
        if (!success) {
            throw new Exception("向基础零件中新增此零件失败，" + materialsNo);
        }
        return true;
    }

    public FunctionResult importGroupPurExcel(MultipartFile file, String orgId) throws Exception {
        FunctionResult result = new FunctionResult();
        //Workbook wb = WorkbookFactory.create(in);
        Workbook wb;//同时兼容Excel-2003及Excel-2007
        try {
            InputStream in = file.getInputStream();
            wb = new HSSFWorkbook(in);
        } catch (Exception ex) {
            // 解决read error异常
            // in = new FileInputStream(file);
            InputStream in = file.getInputStream();
            wb = new XSSFWorkbook(in);
        }
        Sheet sheet = wb.getSheetAt(0);
        int totalRow = sheet.getLastRowNum();
        if (totalRow < 2) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        int totalCell = sheet.getRow(1).getLastCellNum();
        if (totalCell != 3) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        List<MaterialsSearchVO> errorDetailVOList = new ArrayList<>();
        boolean success;
        for (int i = 2; i <= totalRow; i++) {
            //HSSFRow curRow=sheet.getRow(i);
            Row curRow = sheet.getRow(i);
            MaterialsSearchVO detailVO = new MaterialsSearchVO();
            if (curRow == null) {
                continue;
            }
            String no = getCellValue(curRow, 0);
            String materialsNo = getCellValue(curRow, 1);
            String isGroupPur = getCellValue(curRow, 2);
            if (StringUtil.isNullOrEmpty(materialsNo) && StringUtil.isNullOrEmpty(isGroupPur)) {
                break;
            }
            if (StringUtil.isNullOrEmpty(materialsNo)) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("零件编码不能为空");
                errorDetailVOList.add(detailVO);
                continue;
            }
            if (StringUtil.isNullOrEmpty(isGroupPur)) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("是否集购不能为空");
                errorDetailVOList.add(detailVO);
                continue;
            }
            materialsNo = materialsNo.trim();
            isGroupPur = isGroupPur.trim();
            if (!StringUtils.equals(isGroupPur, "0") && !StringUtils.equals(isGroupPur, "1")) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("是否集购只能为1或者0");
                errorDetailVOList.add(detailVO);
                continue;
            }
            PriMaterialsDO priMaterialsDO = priMaterialsMapper.itemByNo(materialsNo, orgId);
            if (priMaterialsDO == null) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("零件不存在");
                errorDetailVOList.add(detailVO);
                continue;
            }
            success = priMaterialsMapper.updateGroupPur(priMaterialsDO.getMaterialsId(), NumberUtils.toInt(isGroupPur)) > 0;
            if (!success) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("零件更新失败:" + materialsNo);
                errorDetailVOList.add(detailVO);
                continue;
            }
        }

        if (ListUtil.isNullOrEmpty(errorDetailVOList)) {
            result.setValue(new ArrayList<>());
            result.setCode(ErrorCode.Success);
        } else {
            result.setValue(errorDetailVOList);
            result.setCode(ErrorCode.IllegalArument);
        }
        return result;
    }

    public void downloadGroupPurExcel() throws Exception {
        FileUtil.downLoadFile(response, filePath, templateGroupPurExcelFileName);
    }

    /**
     * @Des 零件重量模板下载
     * @Date 2020/10/22 16:10
     * @Author wangzhaoyu
     * @Param []
     * @Return void
     */
    public void downloadMaterialWeightExcel() throws Exception {
        FileUtil.downLoadFile(response, filePath, MATERIAL_WEIGHT_EXCELNAME);

    }

    public ErrorCode updateStandardPrice(String materialsNo, String orgId, BigDecimal standardPrice) {
        PriMaterialsDO priMaterialsDO = priMaterialsMapper.itemByNo(materialsNo, orgId);
        if (null == priMaterialsDO) {
            return ErrorCode.MaterialsNotExists;
        }

        PriMaterialsDO materialsDO = new PriMaterialsDO();
        materialsDO.setStandardPrice(standardPrice);
        materialsDO.setMaterialsId(priMaterialsDO.getMaterialsId());
        return priMaterialsMapper.update(materialsDO) > 0 ? ErrorCode.Success : ErrorCode.Failure;
    }
    
    public ErrorCode updateParityPrice(String materialsNo, String orgId, BigDecimal parityPrice) {
        PriMaterialsDO priMaterialsDO = priMaterialsMapper.itemByNo(materialsNo, orgId);
        if (null == priMaterialsDO) {
            return ErrorCode.MaterialsNotExists;
        }
        return priMaterialsMapper.updateParityPrice(materialsNo, orgId, parityPrice) > 0 ? ErrorCode.Success : ErrorCode.Failure;
    }

    public void downloadMaterialsPrice(String orgId) throws Exception {
        CompanyInfoDO companyInfoDO=companyInfoMapper.item(orgId);
        if(companyInfoDO==null){
            return;
        }
        if(companyInfoDO.getCompanyType().equals(CompanyTypeEnum.Type.Company.toString())){
            FileUtil.downLoadFile(response, filePath, templateCompanyPrice);
        }else {
            FileUtil.downLoadFile(response, filePath, templateDealerPrice);
        }

    }

    public FunctionResult importMaterialsPrice(MultipartFile file, String orgId) throws Exception {
        FunctionResult result = new FunctionResult();
        Workbook wb;//同时兼容Excel-2003及Excel-2007
        try {
            InputStream in = file.getInputStream();
            wb = new HSSFWorkbook(in);
        } catch (Exception ex) {
            InputStream in = file.getInputStream();
            wb = new XSSFWorkbook(in);
        }
        Sheet sheet = wb.getSheetAt(0);
        int totalRow = sheet.getLastRowNum();
        if (totalRow < 2) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        int totalCell = sheet.getRow(1).getLastCellNum();
        if (totalCell != 5) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        List<MaterialsSearchVO> errorDetailVOList = new ArrayList<>();
        boolean success;
        for (int i = 2; i <= totalRow; i++) {
            Row curRow = sheet.getRow(i);
            MaterialsSearchVO detailVO = new MaterialsSearchVO();
            if (curRow == null) {
                continue;
            }
            String no = getCellValue(curRow, 0);
            String materialsNo = getCellValue(curRow, 1);
            String standardPrice = getCellValue(curRow, 2);
            String price = getCellValue(curRow, 3);
            String agentPurchasePrice = getCellValue(curRow, 4);
            if (!isBigDecimal(standardPrice) && !isBigDecimal(price) && !isBigDecimal(agentPurchasePrice)) {
                continue;
            }
            if (StringUtil.isNullOrEmpty(materialsNo)) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("零件编码不能为空");
                errorDetailVOList.add(detailVO);
                continue;
            }

            materialsNo = materialsNo.trim();
            standardPrice = standardPrice.trim();
            price = price.trim();
            agentPurchasePrice = agentPurchasePrice.trim();
            PriMaterialsDO priMaterialsDO = priMaterialsMapper.itemByNo(materialsNo, orgId);
            if (priMaterialsDO == null) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("零件不存在");
                errorDetailVOList.add(detailVO);
                continue;
            }
            PriMaterialsDO newPriMaterialsDO=new PriMaterialsDO();
            newPriMaterialsDO.setMaterialsId(priMaterialsDO.getMaterialsId());
            if(isBigDecimal(standardPrice)){
                newPriMaterialsDO.setStandardPrice(new BigDecimal(standardPrice).multiply(new BigDecimal(100)));
            }
            if(isBigDecimal(price)){
                newPriMaterialsDO.setPrice(new BigDecimal(price).multiply(new BigDecimal(100)));
            }
            if(isBigDecimal(agentPurchasePrice)){
                newPriMaterialsDO.setAgentPurchasePrice(new BigDecimal(agentPurchasePrice).multiply(new BigDecimal(100)));
            }
            success = priMaterialsMapper.update(newPriMaterialsDO) > 0;
            if (!success) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("零件更新失败:" + materialsNo);
                errorDetailVOList.add(detailVO);
                continue;
            }
        }

        if (ListUtil.isNullOrEmpty(errorDetailVOList)) {
            result.setValue(new ArrayList<>());
            result.setCode(ErrorCode.Success);
        } else {
            result.setValue(errorDetailVOList);
            result.setCode(ErrorCode.IllegalArument);
        }
        return result;
    }

    private static boolean isBigDecimal(String str){
        if(str==null || str.trim().length() == 0){
            return false;
        }
        char[] chars = str.toCharArray();
        int sz = chars.length;
        int i = (chars[0] == '-') ? 1 : 0;
        if(i == sz)
        {return false;}
        //除了负号，第一位不能为'小数点'
        if(chars[i] == '.')
        {return false;}

        boolean radixPoint = false;
        for(; i < sz; i++){
            if(chars[i] == '.'){
                if(radixPoint)
                {return false;}
                radixPoint = true;
            }else if(!(chars[i] >= '0' && chars[i] <= '9')){
                return false;
            }
        }
        return true;
    }

    /**
     * 查询对应仓库库区下的零件默认储位
     *
     * @param searchVO
     * @return
     */
    public Map<String, String> findDefaultLocation(DefaultLocationSearchVO searchVO) {
        MaterialLocationRelationVO cond;
        Map<String, String> locationMap = new HashMap<>();
        if (null == searchVO || CollectionUtils.isEmpty(searchVO.getMaterialsNos())) {
            return locationMap;
        }
        for (String materialsNo : searchVO.getMaterialsNos()) {
            cond = new MaterialLocationRelationVO();
            cond.setOrgId(searchVO.getOrgId());
            cond.setMaterialNo(materialsNo);
            cond.setWarehouseCode(searchVO.getWarehouseCode());
            cond.setAreaCode(searchVO.getAreaCode());
            locationMap.put(materialsNo, materialLocationRelationMapper.findLocationCode(cond));
        }
        return locationMap;
    }
    
    /**
     * 导入认证件
     * @param in
     * @param orgId
     * @return
     * @throws Exception
     */
    public FunctionResult importAuthDevice(InputStream in, String orgId) throws Exception {
        FunctionResult result = new FunctionResult();
        result.setCode(ErrorCode.Success);
        HSSFWorkbook wb = new HSSFWorkbook(in);
        HSSFSheet sheet = wb.getSheetAt(0);

        int totalRow = sheet.getLastRowNum();
        if (totalRow < 2) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        int totalCell = sheet.getRow(1).getLastCellNum();
        if (totalCell != 2) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        List<PriMaterialsDO> detailDOList = new ArrayList<>();
        List<AuthDeviceOutVO> errorDetailVOList = new ArrayList<>();
        for (int i = 2; i <= totalRow; i++) {
            HSSFRow curRow = sheet.getRow(i);
            AuthDeviceOutVO detailVO = new AuthDeviceOutVO();
            if (curRow == null) {
                continue;
            }
            String materialsNo = getCellValue(curRow, 0);
            String authDeviceStr = getCellValue(curRow, 1);
            if (StringUtil.isNullOrEmpty(materialsNo)) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("零件编码不能为空");
                errorDetailVOList.add(detailVO);
                continue;
            }
            if (!StringUtil.isNullOrEmpty(authDeviceStr)) {
                if (!"1".equals(authDeviceStr.trim()) && !"0".equals(authDeviceStr.trim())) {
                    detailVO.setErrorRow(i + 1);
                    detailVO.setRemark("是否认证件输入错误");
                    errorDetailVOList.add(detailVO);
                    continue;
                }
            }
            MaterialsVO materialsVO = itemByNo(materialsNo, orgId);
            if (materialsVO == null) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("零件不存在");
                errorDetailVOList.add(detailVO);
                continue;
            }
            if(StringUtils.isEmpty(authDeviceStr)) {
                materialsVO.setAuthDevice(0);
            }else {
                materialsVO.setAuthDevice(Integer.parseInt(authDeviceStr));
            }
            PriMaterialsDO materialsDO = new PriMaterialsDO();
            materialsDO.setMaterialsId(materialsVO.getMaterialsId());
            materialsDO.setMaterialsNo(materialsVO.getMaterialsNo());
            materialsDO.setAuthDevice(materialsVO.getAuthDevice());
            detailDOList.add(materialsDO);
        }
        if(ListUtil.isNullOrEmpty(errorDetailVOList)) {
            for (PriMaterialsDO priMaterialsDO : detailDOList) {
                priMaterialsMapper.update(priMaterialsDO);
            }
        } else {
            result.setValue(errorDetailVOList);
            result.setCode(ErrorCode.IllegalArument);
        }
        return result;
    }
    
    public ErrorCode setAuthDeviceLimit(AuthDeviceLimitVO authDeviceLimitVO, String oemOrgId) throws Exception {
        if (StringUtils.isEmpty(authDeviceLimitVO.getOrgId()) || authDeviceLimitVO.getDeviceType() == null) {
            throw new Exception("参数错误");
        }
        String orgId = authDeviceLimitVO.getOrgId();
        CompanyDealerDO companyDealerDO = companyDealerMapper.getDealer(oemOrgId, authDeviceLimitVO.getOrgId());
        if (companyDealerDO != null) {
            AuthDeviceLimitDO authDeviceLimitDO = new AuthDeviceLimitDO();
            authDeviceLimitDO.setOemOrgId(oemOrgId);
            authDeviceLimitDO.setOrgId(orgId);
            authDeviceLimitDO.setId(getId());
            authDeviceLimitDO.setDeviceType(authDeviceLimitVO.getDeviceType());
            authDeviceLimitMapper.insert(authDeviceLimitDO);
            return ErrorCode.Success;
        }
        SecondAgentVO secondAgentVO = secondAgentService.getAgentInfo(oemOrgId, orgId);
        if (secondAgentVO == null) {
            throw new Exception("客户不存在");
        }
        AuthDeviceLimitDO authDeviceLimitDO = new AuthDeviceLimitDO();
        authDeviceLimitDO.setOemOrgId(oemOrgId);
        authDeviceLimitDO.setOrgId(orgId);
        authDeviceLimitDO.setId(getId());
        authDeviceLimitDO.setDeviceType(authDeviceLimitVO.getDeviceType());
        authDeviceLimitMapper.insert(authDeviceLimitDO);
        return ErrorCode.Success;
    }
    
    public ErrorCode unSetAuthDeviceLimit(AuthDeviceLimitVO authDeviceLimitVO, String oemOrgId) throws Exception {
        if (StringUtils.isEmpty(authDeviceLimitVO.getOrgId()) ||
                (authDeviceLimitVO.getDeviceType() == null || (!Integer.valueOf(0).equals(authDeviceLimitVO.getDeviceType()) && !Integer.valueOf(1).equals(authDeviceLimitVO.getDeviceType())))) {
            throw new Exception("参数错误");
        }
        AuthDeviceLimitDO authDeviceLimitDO = new AuthDeviceLimitDO();
        authDeviceLimitDO.setOemOrgId(oemOrgId);
        authDeviceLimitDO.setOrgId(authDeviceLimitVO.getOrgId());
        authDeviceLimitDO.setDeviceType(authDeviceLimitVO.getDeviceType());
        authDeviceLimitMapper.delete(authDeviceLimitDO);
        return ErrorCode.Success;
    }
    
    public PageCommonVO getAuthDeviceLimitList(SearchCommonVO<AuthConditionVO> condition, String oemOrgId) throws Exception {
        Integer proxyType = condition.getFilters().getProxyType();
        if (proxyType == null || (!new Integer(1).equals(proxyType) && !new Integer(2).equals(proxyType))) {
            throw new Exception("参数错误");
        }
//    	Integer deviceType = condition.getFilters().getDeviceType();
//    	if(deviceType == null || (!new Integer(0).equals(deviceType) && !new Integer(1).equals(deviceType))) {
//    		throw new Exception("参数错误");
//    	}
        condition.getFilters().setOemOrgId(oemOrgId);
        if (new Integer(1).equals(proxyType)) {
            return getOneProxyList(condition);
        } else {
            return getSecondProxyList(condition);
        }
    }
    
    private PageCommonVO getSecondProxyList(SearchCommonVO<AuthConditionVO> condition) {
        return secondAgentService.getSecondProxyList(condition);
    }
    
    private PageCommonVO getOneProxyList(SearchCommonVO<AuthConditionVO> condition) {
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        PageHelperPlus.orderBy("d.CREATE_DATE desc");
        List<CompanyDealerSelectedDO> companyBaseSelectedDOs = companyDealerMapper.getOneProxyList(condition.getFilters());
        List<CompanyBaseInfo> companyBaseInfos = new ArrayList<CompanyBaseInfo>();
        PageCommonVO pageCommonVO = new PageCommonVO();
        pageCommonVO.setPageInfo(new PageInfo(companyBaseSelectedDOs));
        if (CollectionUtils.isNotEmpty(companyBaseSelectedDOs)) {
            for (CompanyDealerSelectedDO companyDealerSelectedDO : companyBaseSelectedDOs) {
                CompanyBaseInfo companyBaseInfo = new CompanyBaseInfo();
                companyBaseInfo.setCompanyName(companyDealerSelectedDO.getCompanyName());
                companyBaseInfo.setShortName(companyDealerSelectedDO.getShortName());
                companyBaseInfo.setOrgId(companyDealerSelectedDO.getDealerOrgId());
                companyBaseInfo.setSelectedFlag(companyDealerSelectedDO.getSelectedFlag() > 0 ? 1 : 0);
                companyBaseInfos.add(companyBaseInfo);
            }
        }
        pageCommonVO.setPageInfoList(companyBaseInfos);
        return pageCommonVO;
    }
    
    public List<CompanyInfoVO> getOemInfos(String orgId) {
        List<CompanyInfoDO> companyInfoDOs = companyDealerMapper.getOemInfos(orgId);
        List<CompanyInfoVO> companyInfoVOs = new ArrayList<CompanyInfoVO>();
        if (CollectionUtils.isNotEmpty(companyInfoDOs)) {
            for (CompanyInfoDO companyInfoDO : companyInfoDOs) {
                CompanyInfoVO companyInfoVO = new CompanyInfoVO();
                BeanUtils.copyProperties(companyInfoDO, companyInfoVO);
                companyInfoVOs.add(companyInfoVO);
            }
        }
        return companyInfoVOs;
    }
    
    public List<MarketingActivityVO> getPricePlan(String oemOrgId, String orgId) {
        List<MarketingActivityDO> marketingActivityDOs = marketingActivityService.getPricePlan(oemOrgId, orgId);
        List<MarketingActivityVO> marketingActivityVOs = new ArrayList<MarketingActivityVO>();
        for (MarketingActivityDO marketingActivityDO : marketingActivityDOs) {
            MarketingActivityVO marketingActivityVO = new MarketingActivityVO();
            BeanUtils.copyProperties(marketingActivityDO, marketingActivityVO);
            marketingActivityVOs.add(marketingActivityVO);
        }
        return marketingActivityVOs;
    }
    
    public ErrorCode syncPrice(OemPriceSyncVO oemPriceSyncVO, String orgId) throws Exception {
        if (!checkOemOrgId(oemPriceSyncVO.getOemOrgId(), orgId)) {
            throw new Exception("没有查看此主机厂的权限");
        }
        MarketingActivityDO marketingActivityDO = marketingActivityService.item(oemPriceSyncVO.getPricePlanId());
        if (marketingActivityDO == null) {
            throw new Exception("此价格方案不存在");
        }
        List<AuthDeviceLimitDO> authDeviceLimitDOs = authDeviceLimitMapper.getInfos(oemPriceSyncVO.getOemOrgId(), orgId);
        List<Integer> deviceTypes = new ArrayList<Integer>();
        if (CollectionUtils.isNotEmpty(authDeviceLimitDOs)) {
            for (AuthDeviceLimitDO authDeviceLimitDO : authDeviceLimitDOs) {
                deviceTypes.add(authDeviceLimitDO.getDeviceType());
            }
        }
        List<MarketingMaterialsVO> marketingMaterialsVOs;
        //1:固定价格,2:固定折扣
        if (Integer.valueOf(1).equals(marketingActivityDO.getModeType())) {
            marketingMaterialsVOs = marketingActivityService.getMaterialsByActivityId(oemPriceSyncVO, orgId, oemPriceSyncVO.getOemOrgId(), deviceTypes);
        } else {
            BigDecimal rate = marketingActivityDO.getModeRate();
            if (rate == null) {
                throw new Exception("价格折扣不存在");
            }
            marketingMaterialsVOs = marketingActivityService.getMaterialsPriceByActivityId(oemPriceSyncVO, orgId, oemPriceSyncVO.getOemOrgId(), deviceTypes);
            for (MarketingMaterialsVO marketingMaterialsVO : marketingMaterialsVOs) {
                marketingMaterialsVO.setPrice(marketingMaterialsVO.getPrice().multiply(rate));
            }
        }
        if (CollectionUtils.isEmpty(marketingMaterialsVOs)) {
            return ErrorCode.Success;
        }
        for (MarketingMaterialsVO marketingMaterialsVO : marketingMaterialsVOs) {
            PriMaterialsDO materialsInfo = null;
            try {
                materialsInfo = getInfo(marketingMaterialsVO.getMaterialsNo(), orgId);
            } catch (Exception e) {
                CompanyInfoDO companyInfoDO = companyInfoMapper.item(orgId);
                StringBuffer msgInfo = new StringBuffer();
                msgInfo.append("公司（").append(companyInfoDO.getCompanyName()).append("）中零件（").append(marketingMaterialsVO.getMaterialsNo())
                        .append("）重复或异常，").append("请检查零件后再继续操作");
                log.error(e.getMessage(), e);
                throw new Exception(msgInfo.toString());
            }
            if (materialsInfo == null) {
                PriMaterialsDO materialsDO = new PriMaterialsDO();
                BeanUtils.copyProperties(marketingMaterialsVO, materialsDO);
                materialsDO.setOrgId(orgId);
                materialsDO.setStandardPrice(marketingMaterialsVO.getPrice());
                materialsDO.setPrice(marketingMaterialsVO.getPrice().multiply(oemPriceSyncVO.getPriceRate()).setScale(0, BigDecimal.ROUND_HALF_UP));
                priMaterialsMapper.insert(materialsDO);
            } else {
                materialsInfo.setStandardPrice(marketingMaterialsVO.getPrice());
                materialsInfo.setPrice(marketingMaterialsVO.getPrice().multiply(oemPriceSyncVO.getPriceRate()).setScale(0, BigDecimal.ROUND_HALF_UP));
                priMaterialsMapper.update(materialsInfo);
            }
        }
        return ErrorCode.Success;
    }

    private PriMaterialsDO getInfo(String materialsNo, String orgId) {
        PriMaterialsDO priMaterialsDO = priMaterialsMapper.getInfoByMaterialsNo(materialsNo, orgId);
        return priMaterialsDO;
    }
    
    private boolean checkOemOrgId(String oemOrgId, String orgId) {
        List<CompanyInfoVO> companyInfoVOs = getOemInfos(orgId);
        if (CollectionUtils.isEmpty(companyInfoVOs)) {
            return false;
        }
        for (CompanyInfoVO companyInfoVO : companyInfoVOs) {
            if (oemOrgId.equals(companyInfoVO.getOrgId())) {
                return true;
            }
        }
        return false;
    }
    
    private String getId() throws Exception {
        ActionResult<String> textResult = fastGenClient.textGuid();
        if (textResult == null || textResult.getCode() != 0)
        {
            throw new Exception("生成ID失败!");
        }
        return textResult.getValue();
    }
    
    public void setPullMaterialRecord() throws Exception {
        TaskRecordDO taskRecordDO = new TaskRecordDO();
        taskRecordDO.setId(getId());
        taskRecordDO.setType(String.valueOf(TaskRecordEnum.PULL_MATERIALS.getCode()));
        taskRecordDO.setTypeName(TaskRecordEnum.PULL_MATERIALS.getDesc());
        taskRecordDO.setTime(new Date());
        taskRecordMapper.insert(taskRecordDO);
    }
    
    public void setPushMarketRecord() throws Exception {
        TaskRecordDO taskRecordDO = new TaskRecordDO();
        taskRecordDO.setId(getId());
        taskRecordDO.setType(String.valueOf(TaskRecordEnum.PUSH_MARKETING.getCode()));
        taskRecordDO.setTypeName(TaskRecordEnum.PUSH_MARKETING.getDesc());
        taskRecordDO.setTime(new Date());
        taskRecordMapper.insert(taskRecordDO);
    }
    
    @Transactional(rollbackFor=Exception.class)
    public void pullInfos() throws Exception {
        pullMaterialInfos();
        pullConRecords();
    }

    /**
     * 拉取零件信息
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor=Exception.class)
    public ErrorCode pullMaterialInfos() throws Exception {
//        CompanyInfoDO companyInfoDO = new CompanyInfoDO();
//        companyInfoDO.setCompanyType("1");
//        List<CompanyInfoDO> companyInfoDOs = companyInfoMapper.list(B);
//        if (CollectionUtils.isEmpty(companyInfoDOs) || companyInfoDOs.size() > 1) {
//            throw new Exception("主公司不存在或重复");
//        }
//        ActionResult<Integer> countResult = erpSyncClient.pullMaterialCount();
//        if (ErrorCode.Success.getCode() == countResult.getCode()) {
//            int count = countResult.getValue();
//            if (count > 0) {
//                int pageSize = count / 50 + 1;
//                for (int i = 0; i < pageSize; i++) {
//                    ActionResult<List<MaterialVO>> result = erpSyncClient.pullMaterialInfos();
//                    if (ErrorCode.Success.getCode() == result.getCode()) {
//                        if (result.getValue() != null) {
//                            List<MaterialVO> materialVOs = result.getValue();
//                            mergeMaterialInfos(companyInfoDOs, materialVOs);
//                            erpSyncClient.updateMaterialSyncFlag(result.getValue());
//                            //companyInfoDO = null;
//                            //companyInfoDOs = null;
//                            //result = null;
//                            //pullMaterialInfos();
//                        }
//                    } else {
//                        LogHelper.error(result.getMessage(), result.getCode());
//                        throw new Exception(result.getMessage());
//                    }
//                }
//            }
//        }
        return ErrorCode.Success;
    }

    public void setPullMarketRecord() throws Exception {
        TaskRecordDO taskRecordDO = new TaskRecordDO();
        taskRecordDO.setId(getId());
        taskRecordDO.setType(String.valueOf(TaskRecordEnum.PULL_MARKETING.getCode()));
        taskRecordDO.setTypeName(TaskRecordEnum.PULL_MARKETING.getDesc());
        taskRecordDO.setTime(new Date());
        taskRecordMapper.insert(taskRecordDO);
    }
    
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode pullConRecords() throws Exception {

//        CompanyInfoVO companyInfoDO = new CompanyInfoVO();
//        companyInfoDO.setCompanyType("1");
//        List<CompanyInfoDO> companyInfoDOs = companyInfoMapper.list(companyInfoDO);
//        if (CollectionUtils.isEmpty(companyInfoDOs) || companyInfoDOs.size() > 1) {
//            throw new Exception("主公司不存在或重复");
//        }
//        ActionResult<Integer> countResult = erpSyncClient.pullPriceCount();
//        if (ErrorCode.Success.getCode() == countResult.getCode()) {
//            int count = countResult.getValue();
//            if (count > 0) {
//                int pageSize = count / 50 + 1;
//                for (int i = 0; i < pageSize; i++) {
//                    ActionResult<List<ConRecordVO>> result = erpSyncClient.pullPriceInfos();
//                    if (ErrorCode.Success.getCode() == result.getCode()) {
//                        if (CollectionUtils.isNotEmpty(result.getValue())) {
//                            List<ConRecordVO> conRecordVOs = result.getValue();
//                            for (ConRecordVO conRecordVO : conRecordVOs) {
//                                MarketingActivityDO marketingActivityDO = marketingActivityMapper.findByName(companyInfoDOs.get(0).getOrgId(), conRecordVO.getPriceTypeName());
//                                if (marketingActivityDO == null) {
//                                    marketingActivityDO = convertMarketingActivityDO(conRecordVO, companyInfoDOs);
//                                    marketingActivityMapper.mergeInto(marketingActivityDO);
//                                }
//                                MarketingMaterialsDO marketingMaterialsDO = convertPriceDO(conRecordVO, companyInfoDOs, marketingActivityDO);
//                                marketingMaterialsMapper.mergeInto(marketingMaterialsDO);
//                                if ("代理商含税销售价".equals(marketingActivityDO.getName())) {
//                                    if (marketingMaterialsDO.getPrice() != null) {
//                                        BigDecimal price = marketingMaterialsDO.getPrice().multiply(new BigDecimal(100));
//                                        priMaterialsMapper.updatePrice(marketingMaterialsDO.getPrice(), marketingMaterialsDO.getMaterialsNo(), companyInfoDOs.get(0).getOrgId());
//                                    }
//                                }
//                            }
//                            erpSyncClient.updateConRecodSyncFlag(result.getValue());
//                            //result = null;
//                            //companyInfoDOs = null;
//                            //pullConRecords();
//                        }
//                    } else {
//                        LogHelper.error(result.getMessage(), result.getCode());
//                        throw new Exception(result.getMessage());
//                    }
//                }
//            }
//        }

        return ErrorCode.Success;
    }

    public void pushConRecords() throws Exception {
        List<MarketingActivityDO> marketingActivityDOs = marketingActivityMapper.syncErpList(companyUtil.ynOrgId());
        for (MarketingActivityDO marketingActivityDO : marketingActivityDOs) {
            Integer count = marketingMaterialsMapper.listCountByActivityId(marketingActivityDO.getId());
            if (count > 0) {
//                int size = count / 50;
//                size = (count % 50 > 0) ? (size + 1) : size;
//                for (int i = 0; i < size; i++) {
//                    List<MarketingMaterialsDO> materialsDOs = marketingMaterialsMapper.listMaterialsByActivityId(marketingActivityDO.getId(), i * 50, (i + 1) * 50);
//                    List<ZhConRecordVO> zhConRecordVOs = convertErpVO(materialsDOs, marketingActivityDO.getModeType(), marketingActivityDO.getPriceType(), marketingActivityDO.getModeRate(), marketingActivityDO.getName(), marketingActivityDO.getId());
//                    ActionResult result = erpSyncClient.pushConRecords(zhConRecordVOs);
//                    if (ErrorCode.Success.getCode() != result.getCode()) {
//                        throw new Exception(result.getMessage());
//                    }
//                }
            }
        }
    }

    public List<String> suplierFactoryIds(String factoryIdLike, String orgId) {
       return  priMaterialsMapper.suplierFactoryIds(factoryIdLike, orgId);
    }

    public void downloadPurchaseInbound() throws Exception {
        FileUtil.downLoadFile(response, filePath, templatePurchaseInExcelFileName);
    }

    public Map<String, PriMaterialsDO> queryPriMaterialsByMaterialsNos(List<String> materialsNos, String orgId) {
        Map<String, PriMaterialsDO> r = new HashMap<>();
        Lists.partition(materialsNos, 1000).forEach(item -> {
            List<PriMaterialsDO> list = priMaterialsMapper.selectByMaterialsNos(item, orgId);
            list.forEach(priMaterialsDO -> {
                String mkey = priMaterialsDO.getMaterialsNo();
                r.put(mkey, priMaterialsDO);
            });
        });
        return r;
    }
}
